其他分享
首页 > 其他分享> > 创建一个Excel文件

创建一个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();

        }

 

标签:mySheet,文件,创建,excel,Excel,Value,Range,rownum
来源: https://www.cnblogs.com/wml-it/p/14731030.html