C# 導出 Excel 的各種方法總結


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

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

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();
                }
            }
        }
View Code
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();
        }
View Code

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

 

第二種:使用 Aspose.Cells.dll

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

可以參考:http://www.cnblogs.com/xiaofengfeng/archive/2012/09/27/2706211.html#top

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)
            {

            }
        }
View Code
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();
        }
View Code

設置單元格格式為文本方法:

cell = worksheet.Cells[rowIndex, colIndex + i];
cell.PutValue(colNames[i]);
style = cell.GetStyle();
style.Number = 49;      // 49(text|@) 表示為文本
cell.SetStyle(style);

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

 

第三種: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 的設計。它在只讀數據庫中”,那就去掉這個,問題解決。

public void ExportExcel(DataTable dt)
        {
            OleDbConnection conn = null;
            OleDbCommand cmd = null;

            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.Workbooks;

            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(true);

            try
            {
                //設置區域為當前線程的區域
                dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

                //設置導出文件路徑
                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();

                //由於使用流創建的 excel 文件不能被正常識別,所以只能使用這種方式另存為一下。
                workbook.SaveCopyAs(savePath);


                // Excel 2003 版本連接字符串
                //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + savePath + "';Extended Properties='Excel 8.0;HDR=Yes;'";

                // Excel 2007 以上版本連接字符串
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='"+ savePath + "';Extended Properties='Excel 12.0;HDR=Yes;'";

                //創建連接對象
                conn = new OleDbConnection(strConn);
                //打開連接
                conn.Open();

                //創建命令對象
                cmd = conn.CreateCommand();

                //獲取 excel 所有的數據表。
                //new object[] { null, null, null, "Table" }指定返回的架構信息:參數介紹
                //第一個參數指定目錄
                //第二個參數指定所有者
                //第三個參數指定表名
                //第四個參數指定表類型
                DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

                //因為后面創建的表都會在最后面,所以本想刪除掉前面的表,結果發現做不到,只能清空數據。
                for (int i = 0; i < dtSheetName.Rows.Count; i++)
                {
                    cmd.CommandText = "drop table [" + dtSheetName.Rows[i]["TABLE_NAME"].ToString() + "]";
                    cmd.ExecuteNonQuery();
                }

                //添加一個表,即 Excel 中 sheet 表
                cmd.CommandText = "create table " + dt.TableName + " ([S_Id] INT,[S_StuNo] VarChar,[S_Name] VarChar,[S_Sex] VarChar,[S_Height] VarChar,[S_BirthDate] VarChar,[C_S_Id] INT)";
                cmd.ExecuteNonQuery();

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string values = "";

                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        values += "'" + dt.Rows[i][j].ToString() + "',";
                    }

                    //判斷最后一個字符是否為逗號,如果是就截取掉
                    if (values.LastIndexOf(',') == values.Length - 1)
                    {
                        values = values.Substring(0, values.Length - 1);
                    }

                    //寫入數據
                    cmd.CommandText = "insert into " + dt.TableName + " (S_Id,S_StuNo,S_Name,S_Sex,S_Height,S_BirthDate,C_S_Id) values (" + values + ")";
                    cmd.ExecuteNonQuery();
                }

                conn.Close();
                conn.Dispose();
                cmd.Dispose();

                //加入下面的方法,把保存的 Excel 文件輸出到瀏覽器下載。需要先關閉連接。
                FileInfo fileInfo = new FileInfo(savePath);
                OutputClient(fileInfo);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                workbook.Close(false, Type.Missing, Type.Missing);
                workbooks.Close();
                excel.Quit();

                Marshal.ReleaseComObject(workbook);
                Marshal.ReleaseComObject(workbooks);
                Marshal.ReleaseComObject(excel);

                workbook = null;
                workbooks = null;
                excel = null;

                GC.Collect();
            }
        }
View Code
public void OutputClient(FileInfo file)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            response.ContentType = "application/vnd.ms-excel";

            //導出到 .xlsx 格式不能用時,可以試試這個
            //HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            response.AddHeader("Content-Length", file.Length.ToString());

            response.WriteFile(file.FullName);
            response.Flush();

            response.Close();
        }
View Code

這種方法需要指定一個已經存在的 Excel 文件作為寫入數據的模板,不然的話就得使用流創建一個新的 Excel 文件,但是這樣是沒法識別的,那就需要用到 Microsoft.Office.Interop.Excel.dll 里面的 Microsoft.Office.Interop.Excel.Workbook.SaveCopyAs() 方法另存為一下,這樣性能也就更差了。

使用操作命令創建的表都是在最后面的,前面的也沒法刪除(我是沒有找到方法),當然也可以不再創建,直接寫入數據也可以。

 

第四種:NPOI

NPOI 是 POI 項目的.NET版本,它不使用 Office COM 組件,不需要安裝 Microsoft Office,目前支持 Office 2003 和 2007 版本。

NPOI 是免費開源的,操作也比較方便,下載地址:http://npoi.codeplex.com/

public void ExportExcel(DataTable dt)
        {
            try
            {
                //創建一個工作簿
                IWorkbook workbook = new HSSFWorkbook();

                //創建一個 sheet 表
                ISheet sheet = workbook.CreateSheet(dt.TableName);

                //創建一行
                IRow rowH = sheet.CreateRow(0);

                //創建一個單元格
                ICell cell = null;

                //創建單元格樣式
                ICellStyle cellStyle = workbook.CreateCellStyle();

                //創建格式
                IDataFormat dataFormat = workbook.CreateDataFormat();

                //設置為文本格式,也可以為 text,即 dataFormat.GetFormat("text");
                cellStyle.DataFormat = dataFormat.GetFormat("@");

                //設置列名
                foreach (DataColumn col in dt.Columns)
                {
                    //創建單元格並設置單元格內容
                    rowH.CreateCell(col.Ordinal).SetCellValue(col.Caption);

                    //設置單元格格式
                    rowH.Cells[col.Ordinal].CellStyle = cellStyle;
                }

                //寫入數據
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //跳過第一行,第一行為列名
                    IRow row = sheet.CreateRow(i + 1);

                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        cell = row.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                        cell.CellStyle = cellStyle;
                    }
                }

                //設置導出文件路徑
                string path = HttpContext.Current.Server.MapPath("Export/");

                //設置新建文件路徑及名稱
                string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";

                //創建文件
                FileStream file = new FileStream(savePath, FileMode.CreateNew,FileAccess.Write);

                //創建一個 IO 流
                MemoryStream ms = new MemoryStream();

                //寫入到流
                workbook.Write(ms);

                //轉換為字節數組
                byte[] bytes = ms.ToArray();

                file.Write(bytes, 0, bytes.Length);
                file.Flush();

                //還可以調用下面的方法,把流輸出到瀏覽器下載
                OutputClient(bytes);

                //釋放資源
                bytes = null;

                ms.Close();
                ms.Dispose();

                file.Close();
                file.Dispose();

                workbook.Close();
                sheet = null;
                workbook = null;
            }
            catch(Exception ex)
            {

            }
        }
View Code
public void OutputClient(byte[] bytes)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            response.BinaryWrite(bytes);
            response.Flush();

            response.Close();
        }
View Code
// 2007 版本創建一個工作簿
IWorkbook workbook = new XSSFWorkbook();

// 2003 版本創建一個工作簿
IWorkbook workbook = new HSSFWorkbook();

PS:操作 2003 版本需要添加 NPOI.dll 的引用,操作 2007 版本需要添加 NPOI.OOXML.dll 的引用。

 

第五種:GridView

直接使用 GridView 把 DataTable 的數據轉換為字符串流,然后輸出到瀏覽器下載。

public void ExportExcel(DataTable dt)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            //實例化一個流
            StringWriter stringWrite = new StringWriter();

            //指定文本輸出到流
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            GridView gv = new GridView();
            gv.DataSource = dt;
            gv.DataBind();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    //設置每個單元格的格式
                    gv.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }

            //把 GridView 的內容輸出到 HtmlTextWriter
            gv.RenderControl(htmlWrite);
            
            response.Write(stringWrite.ToString());
            response.Flush();

            response.Close();
        }
View Code

這種方式導出 .xlsx 格式的 Excel 文件時,沒辦法打開。導出 .xls 格式的,會提示文件格式和擴展名不匹配,但是可以打開的。

 

第六種:DataGrid

其實這一種方法和上面的那一種方法幾乎是一樣的。

public void ExportExcel(DataTable dt)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            //實例化一個流
            StringWriter stringWrite = new StringWriter();

            //指定文本輸出到流
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            DataGrid dg = new DataGrid();
            dg.DataSource = dt;
            dg.DataBind();

            dg.Attributes.Add("style", "vnd.ms-excel.numberformat:@");

            //把 DataGrid 的內容輸出到 HtmlTextWriter
            dg.RenderControl(htmlWrite);

            response.Write(stringWrite.ToString());
            response.Flush();

            response.Close();
        }
View Code

 

第七種:直接使用 IO 流

第一種方式,使用文件流在磁盤創建一個 Excel 文件,然后使用流寫入數據。

public void ExportExcel(DataTable dt)
        {
            //設置導出文件路徑
            string path = HttpContext.Current.Server.MapPath("Export/");

            //設置新建文件路徑及名稱
            string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xls";

            //創建文件
            FileStream file = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write);
            
            //以指定的字符編碼向指定的流寫入字符
            StreamWriter sw = new StreamWriter(file, Encoding.GetEncoding("GB2312"));

            StringBuilder strbu = new StringBuilder();

            //寫入標題
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                strbu.Append(dt.Columns[i].ColumnName.ToString() + "\t");
            }
            //加入換行字符串
            strbu.Append(Environment.NewLine);

            //寫入內容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    strbu.Append(dt.Rows[i][j].ToString() + "\t");
                }
                strbu.Append(Environment.NewLine);
            }

            sw.Write(strbu.ToString());
            sw.Flush();
            file.Flush();
            
            sw.Close();
            sw.Dispose();

            file.Close();
            file.Dispose();
        }
View Code

第二種方式,這種方式就不需要在本地磁盤創建文件了,首先創建一個內存流寫入數據,然后輸出到瀏覽器下載。

public void ExportExcel(DataTable dt)
        {
            //創建一個內存流
            MemoryStream ms = new MemoryStream();

            //以指定的字符編碼向指定的流寫入字符
            StreamWriter sw = new StreamWriter(ms, Encoding.GetEncoding("GB2312"));

            StringBuilder strbu = new StringBuilder();

            //寫入標題
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                strbu.Append(dt.Columns[i].ColumnName.ToString() + "\t");
            }
            //加入換行字符串
            strbu.Append(Environment.NewLine);

            //寫入內容
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    strbu.Append(dt.Rows[i][j].ToString() + "\t");
                }
                strbu.Append(Environment.NewLine);
            }

            sw.Write(strbu.ToString());
            sw.Flush();

            sw.Close();
            sw.Dispose();

            //轉換為字節數組
            byte[] bytes = ms.ToArray();

            ms.Close();
            ms.Dispose();

            OutputClient(bytes);
        }
View Code
public void OutputClient(byte[] bytes)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            response.BinaryWrite(bytes);
            response.Flush();

            response.Close();
        }
View Code

這種方法有一個弊端,就是不能設置單元格的格式(至少我是沒有找到,是在下輸了)。

 

第八種:EPPlus

EPPlus 是一個使用 Open Office Xml 格式(xlsx)讀取和寫入 Excel 2007/2010 文件的 .net 庫,並且免費開源。

下載地址:http://epplus.codeplex.com/

第一種方式,先使用文件流在磁盤創建一個 Excel 文件,然后打開這個文件寫入數據並保存。

public void ExportExcel(DataTable dt)
        {
            //新建一個 Excel 文件
            string path = HttpContext.Current.Server.MapPath("Export/");
            string filePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
            FileStream fileStream = new FileStream(filePath, FileMode.Create);

            //加載這個 Excel 文件
            ExcelPackage package = new ExcelPackage(fileStream);

            // 添加一個 sheet 表
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);

            int rowIndex = 1;   // 起始行為 1
            int colIndex = 1;   // 起始列為 1

            //設置列名
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[rowIndex, colIndex + i].Value = dt.Columns[i].ColumnName;

                //自動調整列寬,也可以指定最小寬度和最大寬度
                worksheet.Column(colIndex + i).AutoFit();
            }

            // 跳過第一列列名
            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].Value = dt.Rows[i][j].ToString();
                }

                //自動調整行高
                worksheet.Row(rowIndex + i).CustomHeight = true;
            }

            //設置字體,也可以是中文,比如:宋體
            worksheet.Cells.Style.Font.Name = "Arial";

            //字體加粗
            worksheet.Cells.Style.Font.Bold = true;

            //字體大小
            worksheet.Cells.Style.Font.Size = 12;

            //字體顏色
            worksheet.Cells.Style.Font.Color.SetColor(System.Drawing.Color.Black);

            //單元格背景樣式,要設置背景顏色必須先設置背景樣式
            worksheet.Cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
            //單元格背景顏色
            worksheet.Cells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.DimGray);

            //設置單元格所有邊框樣式和顏色
            worksheet.Cells.Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.ColorTranslator.FromHtml("#0097DD"));

            //單獨設置單元格四邊框 Top、Bottom、Left、Right 的樣式和顏色
            //worksheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            //worksheet.Cells.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);

            //垂直居中
            worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

            //水平居中
            worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

            //單元格是否自動換行
            worksheet.Cells.Style.WrapText = false;

            //設置單元格格式為文本
            worksheet.Cells.Style.Numberformat.Format = "@";

            //單元格自動適應大小
            worksheet.Cells.Style.ShrinkToFit = true;

            package.Save();

            fileStream.Close();
            fileStream.Dispose();

            worksheet.Dispose();
            package.Dispose();
        }
View Code

第二種方式,不指定文件,先創建一個 Excel 工作簿寫入數據之后,可以選擇保存至指定文件(新建文件)、保存為流、獲取字節數組輸出到瀏覽器下載。

public void ExportExcel(DataTable dt)
        {
            //新建一個 Excel 工作簿
            ExcelPackage package = new ExcelPackage();

            // 添加一個 sheet 表
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(dt.TableName);

            int rowIndex = 1;   // 起始行為 1
            int colIndex = 1;   // 起始列為 1

            //設置列名
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[rowIndex, colIndex + i].Value = dt.Columns[i].ColumnName;

                //自動調整列寬,也可以指定最小寬度和最大寬度
                worksheet.Column(colIndex + i).AutoFit();
            }

            // 跳過第一列列名
            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].Value = dt.Rows[i][j].ToString();
                }

                //自動調整行高
                worksheet.Row(rowIndex + i).CustomHeight = true;
            }

            //設置字體,也可以是中文,比如:宋體
            worksheet.Cells.Style.Font.Name = "Arial";

            //字體加粗
            worksheet.Cells.Style.Font.Bold = true;

            //字體大小
            worksheet.Cells.Style.Font.Size = 12;

            //字體顏色
            worksheet.Cells.Style.Font.Color.SetColor(System.Drawing.Color.Black);

            //單元格背景樣式,要設置背景顏色必須先設置背景樣式
            worksheet.Cells.Style.Fill.PatternType = ExcelFillStyle.Solid;
            //單元格背景顏色
            worksheet.Cells.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.DimGray);

            //設置單元格所有邊框樣式和顏色
            worksheet.Cells.Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.ColorTranslator.FromHtml("#0097DD"));

            //單獨設置單元格四邊框 Top、Bottom、Left、Right 的樣式和顏色
            //worksheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin;
            //worksheet.Cells.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);

            //垂直居中
            worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

            //水平居中
            worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

            //單元格是否自動換行
            worksheet.Cells.Style.WrapText = false;

            //設置單元格格式為文本
            worksheet.Cells.Style.Numberformat.Format = "@";

            //單元格自動適應大小
            worksheet.Cells.Style.ShrinkToFit = true;


            ////第一種保存方式
            //string path1 = HttpContext.Current.Server.MapPath("Export/");
            //string filePath1 = path1 + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
            //FileStream fileStream1 = new FileStream(filePath1, FileMode.Create);
            ////保存至指定文件
            //FileInfo fileInfo = new FileInfo(filePath1);
            //package.SaveAs(fileInfo);

            ////第二種保存方式
            //string path2 = HttpContext.Current.Server.MapPath("Export/");
            //string filePath2 = path2 + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
            //FileStream fileStream2 = new FileStream(filePath2, FileMode.Create);
            ////寫入文件流
            //package.SaveAs(fileStream2);


            //創建一個內存流,然后轉換為字節數組,輸出到瀏覽器下載
            //MemoryStream ms = new MemoryStream();
            //package.SaveAs(ms);
            //byte[] bytes = ms.ToArray();

            //也可以直接獲取流
            //Stream stream = package.Stream;

            //也可以直接獲取字節數組
            byte[] bytes = package.GetAsByteArray();

            //調用下面的方法輸出到瀏覽器下載
            OutputClient(bytes);

            worksheet.Dispose();
            package.Dispose();
        }
View Code
public void OutputClient(byte[] bytes)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;

            response.Clear();
            response.ClearHeaders();
            response.ClearContent();

            //response.ContentType = "application/ms-excel";
            response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet";
            response.AppendHeader("Content-Type", "text/html; charset=GB2312");
            response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));

            response.Charset = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");

            response.BinaryWrite(bytes);
            response.Flush();

            response.End();
        }
View Code

這種方法創建文件和輸出到瀏覽器下載都是可以支持 Excel .xlsx 格式的。更多相關屬性設置,請參考:

http://www.cnblogs.com/rumeng/p/3785775.html

 


免責聲明!

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



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