国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C# 各種導出的方法總結

2019-10-29 21:10:29
字體:
來源:轉載
供稿:網友

第一種:使用 Microsoft.Office.Interop.Excel.dll

首先需要安裝 office 的 excel,然后再找到 Microsoft.Office.Interop.Excel.dll 組件,添加到引用。

C#,導出

public void ExportExcel(DataTable dt)    {      if (dt != null)      {        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();        if (excel == null)        {          return;        }        //設置為不可見,操作在后臺執行,為 true 的話會打開 Excel        excel.Visible = false;        //打開時設置為全屏顯式        //excel.DisplayFullScreen = true;        //初始化工作簿        Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;        //新增加一個工作簿,Add()方法也可以直接傳入參數 true        Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);        //同樣是新增一個工作簿,但是會彈出保存對話框        //Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Add(true);        //新增加一個 Excel 表(sheet)        Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];        //設置表的名稱        worksheet.Name = dt.TableName;        try        {          //創建一個單元格          Microsoft.Office.Interop.Excel.Range range;          int rowIndex = 1;    //行的起始下標為 1          int colIndex = 1;    //列的起始下標為 1          //設置列名          for (int i = 0; i < dt.Columns.Count; i++)          {            //設置第一行,即列名            worksheet.Cells[rowIndex, colIndex + i] = dt.Columns[i].ColumnName;            //獲取第一行的每個單元格            range = worksheet.Cells[rowIndex, colIndex + i];            //設置單元格的內部顏色            range.Interior.ColorIndex = 33;            //字體加粗            range.Font.Bold = true;            //設置為黑色            range.Font.Color = 0;            //設置為宋體            range.Font.Name = "Arial";            //設置字體大小            range.Font.Size = 12;            //水平居中            range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;            //垂直居中            range.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;          }          //跳過第一行,第一行寫入了列名          rowIndex++;          //寫入數據          for (int i = 0; i < dt.Rows.Count; i++)          {            for (int j = 0; j < dt.Columns.Count; j++)            {              worksheet.Cells[rowIndex + i, colIndex + j] = dt.Rows[i][j].ToString();            }          }          //設置所有列寬為自動列寬          //worksheet.Columns.AutoFit();          //設置所有單元格列寬為自動列寬          worksheet.Cells.Columns.AutoFit();          //worksheet.Cells.EntireColumn.AutoFit();          //是否提示,如果想刪除某個sheet頁,首先要將此項設為fasle。          excel.DisplayAlerts = false;          //保存寫入的數據,這里還沒有保存到磁盤          workbook.Saved = true;          //設置導出文件路徑          string path = HttpContext.Current.Server.MapPath("Export/");          //設置新建文件路徑及名稱          string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";          //創建文件          FileStream file = new FileStream(savePath, FileMode.CreateNew);          //關閉釋放流,不然沒辦法寫入數據          file.Close();          file.Dispose();          //保存到指定的路徑          workbook.SaveCopyAs(savePath);          //還可以加入以下方法輸出到瀏覽器下載          FileInfo fileInfo = new FileInfo(savePath);          OutputClient(fileInfo);        }        catch(Exception ex)        {        }        finally        {          workbook.Close(false, Type.Missing, Type.Missing);          workbooks.Close();          //關閉退出          excel.Quit();          //釋放 COM 對象          Marshal.ReleaseComObject(worksheet);          Marshal.ReleaseComObject(workbook);          Marshal.ReleaseComObject(workbooks);          Marshal.ReleaseComObject(excel);          worksheet = null;          workbook = null;          workbooks = null;          excel = null;          GC.Collect();        }      }    }public void OutputClient(FileInfo file)    {      HttpContext.Current.Response.Buffer = true;      HttpContext.Current.Response.Clear();      HttpContext.Current.Response.ClearHeaders();      HttpContext.Current.Response.ClearContent();      HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";      //導出到 .xlsx 格式不能用時,可以試試這個      //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";      HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));      HttpContext.Current.Response.Charset = "GB2312";      HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");      HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());      HttpContext.Current.Response.WriteFile(file.FullName);      HttpContext.Current.Response.Flush();      HttpContext.Current.Response.Close();    }

第一種方法性能實在是不敢恭維,而且局限性太多。首先必須要安裝 office(如果計算機上面沒有的話),而且導出時需要指定文件保存的路徑。也可以輸出到瀏覽器下載,當然前提是已經保存寫入數據。

第二種:使用 Aspose.Cells.dll

這個 Aspose.Cells 是 Aspose 公司推出的導出 Excel 的控件,不依賴 Office,商業軟件,收費的。

public void ExportExcel(DataTable dt)    {      try      {        //獲取指定虛擬路徑的物理路徑        string path = HttpContext.Current.Server.MapPath("DLL/") + "License.lic";        //讀取 License 文件        Stream stream = (Stream)File.OpenRead(path);        //注冊 License        Aspose.Cells.License li = new Aspose.Cells.License();        li.SetLicense(stream);        //創建一個工作簿        Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();        //創建一個 sheet 表        Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];        //設置 sheet 表名稱        worksheet.Name = dt.TableName;        Aspose.Cells.Cell cell;        int rowIndex = 0;  //行的起始下標為 0        int colIndex = 0;  //列的起始下標為 0        //設置列名        for (int i = 0; i < dt.Columns.Count; i++)        {          //獲取第一行的每個單元格          cell = worksheet.Cells[rowIndex, colIndex + i];          //設置列名          cell.PutValue(dt.Columns[i].ColumnName);          //設置字體          cell.Style.Font.Name = "Arial";          //設置字體加粗          cell.Style.Font.IsBold = true;          //設置字體大小          cell.Style.Font.Size = 12;          //設置字體顏色          cell.Style.Font.Color = System.Drawing.Color.Black;          //設置背景色          cell.Style.BackgroundColor = System.Drawing.Color.LightGreen;        }        //跳過第一行,第一行寫入了列名        rowIndex++;        //寫入數據        for (int i = 0; i < dt.Rows.Count; i++)        {          for (int j = 0; j < dt.Columns.Count; j++)          {            cell = worksheet.Cells[rowIndex + i, colIndex + j];            cell.PutValue(dt.Rows[i][j]);          }        }        //自動列寬        worksheet.AutoFitColumns();        //設置導出文件路徑        path = HttpContext.Current.Server.MapPath("Export/");        //設置新建文件路徑及名稱        string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";        //創建文件        FileStream file = new FileStream(savePath, FileMode.CreateNew);        //關閉釋放流,不然沒辦法寫入數據        file.Close();        file.Dispose();        //保存至指定路徑        workbook.Save(savePath);        //或者使用下面的方法,輸出到瀏覽器下載。        //byte[] bytes = workbook.SaveToStream().ToArray();        //OutputClient(bytes);        worksheet = null;        workbook = null;      }      catch(Exception ex)      {      }    }public void OutputClient(byte[] bytes)    {      HttpContext.Current.Response.Buffer = true;      HttpContext.Current.Response.Clear();      HttpContext.Current.Response.ClearHeaders();      HttpContext.Current.Response.ClearContent();      HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";      HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));      HttpContext.Current.Response.Charset = "GB2312";      HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("GB2312");      HttpContext.Current.Response.BinaryWrite(bytes);      HttpContext.Current.Response.Flush();      HttpContext.Current.Response.Close();    }

第二種方法性能還不錯,而且操作也不復雜,可以設置導出時文件保存的路徑,還可以保存為流輸出到瀏覽器下載。

第三種:Microsoft.Jet.OLEDB

這種方法操作 Excel 類似于操作數據庫。下面先介紹一下連接字符串:

// Excel 2003 版本連接字符串string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/xxx.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=2;'";// Excel 2007 以上版本連接字符串string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/xxx.xlsx;Extended Properties='Excel 12.0;HDR=Yes;IMEX=2;'";

Provider:驅動程序名稱

Data Source:指定 Excel 文件的路徑

Extended Properties:Excel 8.0 針對 Excel 2000 及以上版本;Excel 12.0 針對 Excel 2007 及以上版本。

HDR:Yes 表示第一行包含列名,在計算行數時就不包含第一行。NO 則完全相反。

IMEX:0 寫入模式;1 讀取模式;2 讀寫模式。如果報錯為“不能修改表 sheet1 的設計。它在只讀數據庫中”,那就去掉這個,問題解決。

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網!


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 盐源县| 集贤县| 红桥区| 泽州县| 濉溪县| 巴楚县| 绥德县| 农安县| 潮安县| 崇文区| 永春县| 新建县| 三明市| 依安县| 班戈县| 南溪县| 翼城县| 潼关县| 大田县| 绥江县| 禹城市| 清水县| 崇左市| 隆化县| 峡江县| 绵阳市| 辉县市| 汕头市| 疏附县| 陕西省| 甘肃省| 安宁市| 银川市| 临高县| 永安市| 关岭| 马山县| 乐清市| 东明县| 夏津县| 陆川县|