C#實現建立Excel文件,填充數據後保存 直接代碼,相關註釋見下代碼: static void Main(string[] args) { string filePath = @"F:\Test\Excel\"; CreateExcel(filePath); } public static voi ...
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;
顏色對應值見下圖: