C#实现建立Excel文件,填充数据后保存

C#实现建立Excel文件,填充数据后保存

直接代码,相关注释见下代码:

static void Main(string[] args)
        {
            string filePath = @"F:\Test\Excel\";
            CreateExcel(filePath);
        }
        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.Range["A1", "D1"].Interior.ColorIndex = 6;

颜色对应值见下图:

 

posted on 2020-05-19 10:35  農碼一生  阅读(346)  评论(0编辑  收藏

导航

统计