创建一个Excel文件

创建一个Excel文件

   /// <param name="filePath">filePath 为Excel保存的路径</param>
        public static void CreateExcel(string filePath)
        {

            Excel.Application excel = new Excel.Application();
            //EXCEL读写是否可见
            excel.Visible = false;

            excel.Application.Workbooks.Add();
            Excel.Workbook myBook;
            Excel.Worksheet mySheet;
            myBook = excel.Workbooks[1];
            mySheet = (Excel.Worksheet)myBook.ActiveSheet;
            //页签名
            mySheet.Name = "Student";

            mySheet.Cells.Select();
            mySheet.Cells.NumberFormatLocal = "@";
            mySheet.Cells.EntireColumn.AutoFit();

            #region 单元格属性以及列名
            //字体选择
            mySheet.Cells.Font.Name = "Ink Free";// Arial
            //字号大小
            mySheet.Cells.Font.Size = 9;
            //表头字体加粗
            mySheet.Range["A1", "D1"].Font.Bold = true;
            //表头颜色
            mySheet.Range["A1", "D1"].Interior.ColorIndex = 6;
            //建立EXCE栏位表头
            mySheet.Range["A1"].Value = "USER_NAME";
            mySheet.Range["B1"].Value = "USER_ID";
            mySheet.Range["C1"].Value = "SEX";
            mySheet.Range["D1"].Value = "BIRTHDAY";
            #endregion

            #region 添加数值
            //必须从第2行开始添加数值
            for (int rownum = 2; rownum < 5; rownum++)
            {
                mySheet.Range["A" + rownum.ToString()].Value = "Jane";
                mySheet.Range["B" + rownum.ToString()].Value = "202005190" + rownum;
                mySheet.Range["C" + rownum.ToString()].Value = "女";
                mySheet.Range["D" + rownum.ToString()].Value = "2020051" + rownum;
            }
            #endregion
            excel.DisplayAlerts = true;
            excel.AlertBeforeOverwriting = true;
            //保存路径
            string path = filePath + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
            //保存Excel
            myBook.Close(true, path, null);
            //退出Excel
            excel.Quit();

        }

 

上一篇:Group by分组,为分组后的数据添加序号


下一篇:There are multiple modules with names that only differ in casing. 黄色warning