DataSet数据导出为Excel文档(每个DataTable为一个Sheet)

Web项目中,很多时候须要实现将查询的数据集导出为Excel文档的功能,很多时候不希望在工程中添加对Office组件相关的DLL的引用,甚至有时候受到Office不同版本的影响,导致在不同的服务器上部署后功能受限,或和其它项目冲突,那么,使用这种简单粗暴的方式,可能会解决部分猿类灵长动物的烦恼忧愁。

/// 
/// DataSet导出到Excel文件(多个Sheet)
/// 
/// DataSet
/// 文件名称
/// 导出是否成功
public static bool DataSetToExcel(DataSet dataSet, string fileName)
{
    if (dataSet == null) return false;
    if (dataSet.Tables.Count < 1) return false;
    if (dataSet.Tables[0] == null) return false;
    if (string.IsNullOrWhiteSpace(fileName)) return false;
    try
    {
        ExecDataSetToExcel(dataSet, fileName);
        return true;
    }
    catch (Exception ex)
    {
        //DO LOG
        return false;
    }
}
//执行 DataSet 导出
private static void ExecDataSetToExcel(DataSet dataSet, string fileName)
{
    HttpResponse httpResponse = HttpContext.Current.Response;
    httpResponse.Clear();
    httpResponse.Charset = "utf-8";
    httpResponse.ContentType = "text/xml";
    httpResponse.ContentEncoding = System.Text.Encoding.UTF8;
    httpResponse.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8) + ".xls");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < dataSet.Tables.Count; i++)
    {
        System.Data.DataTable dt = dataSet.Tables[i];
        //新建Sheet
        string sheetName = string.IsNullOrWhiteSpace(dt.TableName) ? "Sheet" + (i + 1) : dt.TableName;
        sb.Append("");
        sb.Append("");
        //输出标题行
        sb.Append("");
        for (int j = 0; j < dt.Columns.Count; j++) sb.Append("" + dt.Columns[j].ColumnName + "");
        sb.Append("");
        //输入内容行for (int k = 0; k < dt.Rows.Count; k++)
        {
            sb.Append("");
            for (int l = 0; l < dt.Columns.Count; l++)
            {
                //Type ct = dt.Columns[l].DataType;
                //sb.Append("" + dt.Rows[k][l] + ""); //数字类型
                sb.Append("" + dt.Rows[k][l] + "");
            }
            sb.Append("");
        }
        sb.Append("
"); sb.Append(""); } string excelXmlDoc = CreateExcelXmlDoc(sb.ToString()); httpResponse.Write(excelXmlDoc); httpResponse.Flush(); httpResponse.End(); }
//创建Excel文档对应的XML字符串
private static string CreateExcelXmlDoc(string worksheetXml)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("");
    sb.Append(""
        +"xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'"
        +"xmlns:html='http://www.w3.org/TR/REC-html40'>");
    //文档属性
    sb.Append(""
        + "UnitechUnitech12.00"
        + "");
    //样式
    sb.Append("");
    sb.Append("");
    sb.Append("");
    sb.Append("");
    //Work Sheet
    sb.Append(worksheetXml);
    sb.Append("");
    return sb.ToString();
}

有需要的拿去自己进行改进和优化吧。

 

转载于:https://www.cnblogs.com/dannyli/p/3985461.html

你可能感兴趣的:(DataSet数据导出为Excel文档(每个DataTable为一个Sheet))