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;
颜色对应值见下图:
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/12915508.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。