1. 程式人生 > >c#讀取生成excel表格檔案xls、xlsx格式檔案

c#讀取生成excel表格檔案xls、xlsx格式檔案

全棧工程師開發手冊 (作者:欒鵬)

c#儲存生成excel表格格式xls、xlsx格式的檔案

需要電腦安裝對應版本的office,並且在專案中引用excel

測試程式碼

static void Main()
{
    List<string> alldata = new List<string>();
    alldata.Add("第一行");
    alldata.Add("第2行");
    alldata.Add("第叄行");
    list2excel(alldata,"列名","test.xls");
}

list<string>

生成表格的函式

//匯出到execl,需要匯入Microsoft.Office.Interop.Excel
        public static void list2excel(List<String> strarray,string column_name,string path)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add(column_name, System.Type.GetType("System.String"
)); foreach ( String str in strarray) { DataRow dr = dt.NewRow(); dr[0] = str; dt.Rows.Add(dr); } DataTabletoExcel(dt, path); }

將DataTable生成excel函式

public static bool DataTabletoExcel(System.Data
.DataTable dt, string AbosultedFilePath) { if (dt == null) return false; Microsoft.Office.Interop.Excel.Application excApp = new Microsoft.Office.Interop.Excel.Application(); if (excApp==null) { MessageBox.Show("無法建立excel物件,可能您的電腦未安裝excel"); return false; } Microsoft.Office.Interop.Excel.Workbook workBook = excApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet workSeet = workBook.Worksheets[1]; //取得sheet1 Microsoft.Office.Interop.Excel.Range range = null; int tableCount = dt.Rows.Count; int rowRead = 0; float percent = 0; for (int i = 0; i < dt.Columns.Count; i++) { workSeet.Cells[1, i + 1] = dt.Columns[i].ColumnName; //設定標題的樣式 range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[1, i + 1]; range.Font.Bold = true; //粗體 range.Font.Size = "12";//字型大小 range.Font.Name = "宋體"; range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //居中 range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //背景色 range.EntireColumn.AutoFit(); //自動設定列寬 range.EntireRow.AutoFit(); //自動設定行高 } for (int r = 0; r < dt.Rows.Count; r++) { for (int c = 0; c < dt.Columns.Count; c++) { //寫入內容 workSeet.Cells[r + 2, c + 1] = "'" + dt.Rows[r][c].ToString(); //設定樣式 range = (Microsoft.Office.Interop.Excel.Range)workSeet.Cells[r + 2, c + 1]; range.Font.Size = 9; //字型大小 range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null); //加邊框 range.EntireColumn.AutoFit(); //自動調整列寬 } rowRead++; percent = ((float)(100 * rowRead)) / tableCount; System.Windows.Forms.Application.DoEvents(); } range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin; if (dt.Columns.Count > 1) { range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin; } try { workBook.Saved = true; workBook.SaveCopyAs(AbosultedFilePath); } catch { } workBook.Close(); if (excApp != null) { excApp.Workbooks.Close(); excApp.Quit(); int generation = System.GC.GetGeneration(excApp); System.Runtime.InteropServices.Marshal.ReleaseComObject(excApp); excApp = null; System.GC.Collect(generation); } GC.Collect(); //強行銷燬 #region 強行殺死最近開啟的Excel程序 System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL"); System.DateTime startTime = new DateTime(); int m, killID = 0; for (m = 0; m < excelProc.Length; m++) { if (startTime < excelProc[m].StartTime) { startTime = excelProc[m].StartTime; killID = m; } } if (excelProc[killID].HasExited == false) { excelProc[killID].Kill(); } #endregion return true; }