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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM