DataTable導出到Excel

簡單的導出到Excel中:html

代碼以下:app

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
namespace  Space
{
    /// <summary>
    /// 標題:將 DataSet, DataTable 導出到 Excel
    /// 描述:對以前作的導出 Excel 作調整以支持對 DataSet 及 DataTable 的導出;
    /// DataSet     導出時能夠指定須要導出的 DataTable
    /// DataTable   導出時能夠指定須要導出的 DataColumn 及自定義導出後的列名
    /// </summary>
    public static class ExcelExportProvider
    {
        public static string BuildExportHTML(System.Data.DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;
            int pagerecords = 50000;
            result = "<?xml version=\"1.0\" encoding=\"gb2312\"?>";
            result += "<?mso-application progid=\"Excel.Sheet\"?>";
            result += "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
            result += "xmlns:o=\"urn:schemas-microsoft-com:office:office\" ";
            result += "xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ";
            result += "xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ";
            result += "xmlns:html=\"http://www.w3.org/TR/REC-html40\"> ";
            string strTitleRow = "";
            //設置每行的標題行
            strTitleRow = "<Row ss:AutoFitHeight='0'>";
            for (int j = 0; j < colCount; j++)
            {
                var tempColName = dt.Columns[j].ColumnName;
                if (tempColName.IndexOf("@@@@@@@@@@@@") >= 0)   //把"@@@@@@@@@@@@"做爲分隔符號 前面爲顯示內容,後面爲主鍵id。
                {
                    tempColName = tempColName.Split(new string[] { "@@@@@@@@@@@@" }, StringSplitOptions.None)[0];
                }
                strTitleRow += "<Cell><Data ss:Type=\"String\">" + tempColName + "</Data></Cell>";
            }
            strTitleRow += "</Row>";
            StringBuilder strRows = new StringBuilder();
            //在變長的字符操做方面stringbuilder的效率比string高得多
            int page = 1;    //分紅的sheet數
            int cnt = 1;        //輸入的記錄數
            int sheetcolnum = 0;        //每一個sheet的行數,其實就等於cnt+1
            for (int i = 0; i < readCnt; i++)
            {
                strRows.Append("<Row ss:AutoFitHeight=\"0\">");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append("<Cell><Data ss:Type=\"String\">" + Convert.ToDateTime(dt.Rows[i][j].ToString()).ToShortDateString() + "</Data></Cell>");
                        }
                        else
                            strRows.Append("<Cell><Data ss:Type=\"String\"></Data></Cell>");
                    }
                    //alter by taomin 2012-11-13 新增decimal類型數據的處理方式 避免decimal類型數據導入EXCEL是未被轉化爲數字型,不利於在excel中進行統計計算
                    else if (dt.Columns[j].DataType.Name == "Int32" || dt.Columns[j].DataType.Name == "Int64" || dt.Columns[j].DataType.Name.ToLower() == "decimal")
                    {
                        strRows.Append("<Cell><Data ss:Type= \"Number\">" + dt.Rows[i][j].ToString().Trim() + "</Data></Cell>");
                    }
                    else
                    {
                        strRows.Append("<Cell><Data ss:Type=\"String\">" + dt.Rows[i][j].ToString().Trim() + "</Data></Cell>");
                    }
                }
                strRows.Append("</Row>");
                cnt++;
                //到設定行數時,要輸出一頁,防止office打不開,同時要注意string和stringbuilder的長度限制
                if (cnt >= pagerecords + 1)
                {
                    sheetcolnum = cnt + 1;
                    result += "<Worksheet ss:Name=\"Sheet" + page.ToString() + "\"><Table ss:ExpandedColumnCount=\"" + colCount.ToString() + "\" ss:ExpandedRowCount=\"" + sheetcolnum.ToString() + "\" x:FullColumns=\"1\" x:FullRows=\"1\" ss:DefaultColumnWidth=\"104\" ss:DefaultRowHeight=\"13.5\">" + strTitleRow.ToString() + strRows.ToString() + "</Table></Worksheet>";
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;                     //下一個sheet從新計數
                    page++;
                }
            }
            sheetcolnum = cnt + 1;
            result = result + "<Worksheet ss:Name='Sheet" + page.ToString() + "'><Table ss:ExpandedColumnCount='" + colCount.ToString() + "' ss:ExpandedRowCount='" + sheetcolnum.ToString() + "' x:FullColumns='1' x:FullRows='1' ss:DefaultColumnWidth='104' ss:DefaultRowHeight='13.5'>" + strTitleRow.ToString() + strRows.ToString() + "</Table></Worksheet></Workbook>";
            return result;
        }
        /// <summary>
        /// 導出Excel
        /// 例子 Controller裏面調用 ExcelExportProvider.DataTable2Excel(dt, "ClickExcel.xls");
        /// </summary>
        public static void DataTable2Excel(DataTable dt, string fileName)
        {
            string outputFileName = null;
            HttpContext curContext = System.Web.HttpContext.Current;
            string browser = curContext.Request.UserAgent.ToUpper();
            if (browser.Contains("FIREFOX") == true)
            {
                outputFileName = "\"" + fileName + "\"";
            }
            else
            {
                outputFileName = HttpUtility.UrlEncode(fileName);
            }
            curContext.Response.ContentType = "application/ms-excel";
            curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + outputFileName));
            curContext.Response.Charset = "";
            curContext.Response.Write(BuildExportHTML(dt));
            curContext.Response.Flush();
            curContext.Response.End();
        }
    }
}
View Code
使用方法:
前臺:
eg:<button id="ExportToExcel">導出到Excel</button>
 
$("#ExportToExcel").click(function(){
     Location.href= "/ExportToExcel.do"
});
 
後臺:
public void ExportToExcel(DataTable dt)
{
    string fileName = "test.xls";
    ExcelExportProvider.DataTable2Excel(dt,fileName);
}

 

點擊Button時會調用資源管理器的路徑選擇對話框,在此時選擇文件存儲路徑ide

 

PS:轉載請註明出處。ui

相關文章
相關標籤/搜索