C/C++教程

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

        }

 

这篇关于创建一个Excel文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!