1. 程式人生 > 實用技巧 >C# 如何將DataTable轉成Excel檔案(利用Aspose.Cells.dll外掛生成)

C# 如何將DataTable轉成Excel檔案(利用Aspose.Cells.dll外掛生成)

由於剛開始使用檔案流匯出Excel檔案,微軟Excel開啟報安全警告問題,WPS不會,微軟Excel會,所有利用第三方插入Aspose.Ceils.dll插入做Excel匯出

優點:不需要安裝微軟Excel這些,只需引用Aspose.Ceils.dll,就可以了

1、下載Aspose.Cell.dll

http://www.xdowns.com/app/309341.html

2、整體demo

1)匯出Excel方法

  public static class ExportHelper
    {
        /// <summary>
        /// DataTable資料生成Excel檔案(用檔案流(StreamWriter)寫入,棄用原因:微軟Excel開啟報安全警告問題,WPS不會,微軟Excel會 )
        
/// </summary> /// <param name="tab">DataTable資料來源</param> /// <param name="path">儲存檔案路徑(包含檔名)</param> public static void CreateExcelByFileStream(DataTable tab, string path) { try { StreamWriter sw = new StreamWriter(path, false
, Encoding.GetEncoding("gb2312")); StringBuilder sb = new StringBuilder(); for (int k = 0; k < tab.Columns.Count; k++) { sb.Append(tab.Columns[k].ColumnName.ToString() + "\t"); } sb.Append(Environment.NewLine);
for (int i = 0; i < tab.Rows.Count; i++) { for (int j = 0; j < tab.Columns.Count; j++) { sb.Append(tab.Rows[i][j].ToString() + "\t"); } sb.Append(Environment.NewLine);//每寫一行資料後換行 } sw.Write(sb.ToString()); sw.Flush(); sw.Close();//釋放資源 } catch (Exception ex) { //MessageBox.Show(ex.Message); } } /// <summary> /// DataTable資料生成Excel檔案(呼叫第三方Aspose.Cells.dll外掛) /// </summary> /// <param name="data">匯入Excel的dataTable資料來源</param> /// <param name="filepath">儲存的檔案路徑</param> public static void CreateExcelByAsposeCells(DataTable data, string filepath) { try { //Workbook book = new Workbook("E:\\test.xlsx"); //開啟工作簿 Workbook book = new Workbook(); //建立工作簿 Worksheet sheet = book.Worksheets[0]; //建立工作表 Cells cells = sheet.Cells; //單元格 //建立 列名行的樣式 Style style = book.Styles[book.Styles.Add()]; style.Borders[BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 左邊界線 style.Borders[BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 右邊界線 style.Borders[BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 上邊界線 style.Borders[BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 下邊界線 style.HorizontalAlignment = TextAlignmentType.Center; //單元格內容的水平對齊方式文字居中 style.Font.Name = "宋體"; //字型 style.Font.IsBold = true; //設定粗體 style.Font.Size = 12; //設定字型大小 style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0); //背景色 style.Pattern = Aspose.Cells.BackgroundType.Solid; //背景樣式 style.IsTextWrapped = true; //單元格內容自動換行 //建立 資料行的樣式 Style conStyle = book.Styles[book.Styles.Add()]; conStyle.Borders[BorderType.LeftBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 左邊界線 conStyle.Borders[BorderType.RightBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 右邊界線 conStyle.Borders[BorderType.TopBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 上邊界線 conStyle.Borders[BorderType.BottomBorder].LineStyle = Aspose.Cells.CellBorderType.Thin; //應用邊界線 下邊界線 conStyle.Font.Name = "宋體"; conStyle.HorizontalAlignment = TextAlignmentType.Left; //單元格內容的水平對齊方式文字居中 conStyle.Font.IsBold = false; conStyle.Font.Size = 11; //表格填充資料 int Colnum = data.Columns.Count;//表格列數 int Rownum = data.Rows.Count;//表格行數 //生成行 列名行 for (int i = 0; i < Colnum; i++) { cells[0, i].PutValue(data.Columns[i].ColumnName); //新增表頭 cells[0, i].SetStyle(style); //新增樣式 //cells.SetColumnWidth(i, data.Columns[i].ColumnName.Length * 2 + 1.5); //自定義列寬 //cells.SetRowHeight(0, 30); //自定義高 } //生成資料行 for (int i = 0; i < Rownum; i++) { for (int k = 0; k < Colnum; k++) { cells[1 + i, k].PutValue(data.Rows[i][k].ToString()); //新增資料 cells[1 + i, k].SetStyle(conStyle); //新增樣式 style } } sheet.AutoFitColumns(); //自適應寬 book.Save(filepath); //儲存 GC.Collect(); } catch (Exception e) { //logger.Error("生成excel出錯:" + e.Message); } } }

2)呼叫方法

 public class HomeController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            //呼叫匯出方法
            ExportExcel();
            return View();
        }

       /// <summary>
       /// 將DataTable轉成Excel檔案
       /// </summary>
        public void ExportExcel() {
            //獲取tab資料
            DataTable tabs = GetDataTableDemo();
            //呼叫檔案流匯出方法(微軟Excel開啟報安全警告問題,WPS不會,微軟Excel會
//ExportHelper.CreateExcelByFileStream(tabs, "D:\\Excel匯出測試.xlsx");
//呼叫AsposeCells.dll執行匯出的資料 ExportHelper.CreateExcelByAsposeCells(tabs, "D:\\Excel匯出測試.xlsx"); } /// <summary> /// 定義DataTable資料來源 /// </summary> /// <returns></returns> public DataTable GetDataTableDemo() { //定義列資料 DataTable tab = new DataTable(); tab.Columns.Add("ID", typeof(int)); tab.Columns.Add("學號", typeof(string)); tab.Columns.Add("名稱", typeof(string)); tab.Columns.Add("性別", typeof(string)); tab.Columns.Add("班級", typeof(string)); //新增列的資料 for (int i = 0; i < 10; i++) { DataRow row = tab.NewRow(); //新增每行的資料 row["ID"] = (i + 1); row["學號"] = (i + 1).ToString().PadLeft(4, '0'); row["名稱"] = "學生" + (i + 1); row["性別"] = (i + 1) % 2 == 0 ? "" : ""; row["班級"] = (i + 1) % 2 == 0 ? "重點班" : "普通班"; //新增到datatable中 tab.Rows.Add(row); } return tab; } }

3、執行專案,檢視結果

4、Demo原始碼下載

連結:https://pan.baidu.com/s/15qqjFPup5spbzUR9KsZhLQ
提取碼:1234