日期:2014-05-18  浏览次数:20404 次

如何将 DataTable 直接生成 Excel
如何将 DataTable 生成Excel ??

我说的是在后台直接将 DataTable 生成 Excel 文件

------解决方案--------------------
网上有很多方法, Such as

C# code

/// <summary>
/// 生成Excel文件
/// </summary>
/// <param name="ds">数据集</param>
/// <param name="fileName">生成文件名</param>
private void CreateExcel(DataTable dt, string fileName)
{
    HttpResponse resp;
    resp = Page.Response;
    resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
    resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
    string colHeaders = "", ls_item = "";

    ////定义表对象与行对象,同时用DataSet对其值进行初始化
    //DataTable dt = ds.Tables[0];
    DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
    int i = 0;
    int cl = dt.Columns.Count;

    //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
    for (i = 0; i < cl; i++)
    {
        if (i == (cl - 1))//最后一列,加n
        {
            colHeaders += dt.Columns[i].Caption.ToString() + "\n";
        }
        else
        {
            colHeaders += dt.Columns[i].Caption.ToString() + "\t";
        }

    }
    resp.Write(colHeaders);
    //向HTTP输出流中写入取得的数据信息

    //逐行处理数据 
    foreach (DataRow row in myRow)
    {
        //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   
        for (i = 0; i < cl; i++)
        {
            if (i == (cl - 1))//最后一列,加n
            {
                ls_item += row[i].ToString() + "\n";
            }
            else
            {
                ls_item += row[i].ToString() + "\t";
            }

        }
        resp.Write(ls_item);
        ls_item = "";

    }
    resp.End(); 
}

------解决方案--------------------
public static bool ExportToExcel(DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
{
Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
Excel.Workbook obook = null;
Excel.Worksheet oSheet = null;
Excel.Range range = null;
#endregion
try
{
obook = oExcel.Workbooks.Add("");
oSheet = (Excel.Worksheet)obook.Worksheets[1];
int rCount, cCount;
rCount = table.Rows.Count;
cCount = table.Columns.Count;
object obj = System.Reflection.Missing.Value;

if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
{
throw new ArgumentOutOfRangeException("columnIndexs 与 columnHeads 长度必须一致。");
}
for (int i = 1; i <= columnIndexs.Length; i++)
{

range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
range.NumberFormatLocal = "@";
}
for (int c = 0; c < columnIndexs.Length; c++)
{
oSheet.Cells[1, c + 1] = columnHeads[c];
for (int r = 1; r <= rCount; r++)
{
oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
}
}
obook.SaveCopyAs(excelName);
obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
return true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
ystem.Runtime.InteropServices.Marshal.ReleaseComObject(range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);