public static string CreateExcel(DataTable dt, string FileName, string path, string columns)         {

string excelPath = path + "Code\\ZipExcel\\" + FileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".xlsx";

string connString = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelPath + ";Extended Properties='Excel 12.0 xml; HDR=Yes; IMEX=0;'";             if (dt == null)             {                 return "";             }

int rows = dt.Rows.Count;             int cols = dt.Columns.Count;             StringBuilder sb;

if (rows == 0)             {                 return "";             }

sb = new StringBuilder();

//生成创建表的脚本             sb.Append("CREATE TABLE ");             sb.Append("[ReportData] " + " ( ");

for (int i = 0; i < cols; i++)             {                 if (i < cols - 1)                     if (columns.IndexOf(dt.Columns[i].ColumnName) > -1)                     {                         sb.Append(string.Format(" [{0}] Numeric(18,2),", dt.Columns[i].ColumnName));                     }                     else                     {                         sb.Append(string.Format(" [{0}] Varchar,", dt.Columns[i].ColumnName));                     }

else                     if (columns.IndexOf(dt.Columns[i].ColumnName) > -1)                     {                         sb.Append(string.Format(" [{0}] Numeric(18,2))", dt.Columns[i].ColumnName));                     }                     else                     {                         sb.Append(string.Format(" [{0}] Varchar )", dt.Columns[i].ColumnName));                     }

}

OleDbConnection objConn = new OleDbConnection(connString);             OleDbCommand objCmd = new OleDbCommand();             objCmd.Connection = objConn;

objCmd.CommandText = sb.ToString();

//try             //{             objConn.Open();             objCmd.ExecuteNonQuery();

//}             //catch (Exception e)             //{             //    return "";

//}

//生成插入数据脚本#region 生成插入数据脚本             sb.Remove(0, sb.Length);             sb.Append("INSERT INTO ");             sb.Append("[ReportData]" + " ( ");

for (int i = 0; i < cols; i++)             {                 if (i < cols - 1)                     sb.Append("[" + dt.Columns[i].ColumnName + "]" + ",");                 else                     sb.Append("[" + dt.Columns[i].ColumnName + "]" + ") values (");             }

for (int i = 0; i < cols; i++)             {                 if (i < cols - 1)                     sb.Append("@" + "para" + i.ToString() + ",");

else                     sb.Append("@" + "para" + i.ToString() + ")");             }             //#endregion

//建立插入动作的Command             objCmd.CommandText = sb.ToString();             OleDbParameterCollection param = objCmd.Parameters;

for (int i = 0; i < cols; i++)             {                 if (columns.IndexOf(dt.Columns[i].ColumnName) > -1)                 {                     param.Add(new OleDbParameter("@" + "para" + i.ToString(), OleDbType.Numeric));                 }                 else                 {                     param.Add(new OleDbParameter("@" + "para" + i.ToString(), OleDbType.VarChar));                 }             }

int curRow = 0;

//遍历DataTable将数据插入新建的Excel文件中             foreach (DataRow row in dt.Rows)             {

for (int i = 0; i < param.Count; i++)                 {                     if (columns.IndexOf(dt.Columns[i].ColumnName) > -1)                     {                         if (row[i] == null || row[i].ToString() == "")                         {                             param[i].Value = 0;                         }                         else                         {                             param[i].Value = row[i];                         }

}                     else                     {                         param[i].Value = row[i];                     }

}

objCmd.ExecuteNonQuery();

curRow = curRow + 1;             }

objConn.Close();

return excelPath;         }         public static void DataTableToExcel(DataTable dt, string FileName, string path, string columns)         {             ArrayList filelist = new ArrayList();             string IsZip = "";             string excelPath = "";             if (dt.Rows.Count < 50000)             {                 IsZip = "0";                 excelPath = Kit.CreateExcel(dt, FileName, path, columns);             }             else if (dt.Rows.Count < 1000000)             {                 IsZip = "1";                 excelPath = Kit.CreateExcel(dt, FileName, path, columns);                 if (excelPath != "")                 {                     filelist.Add(excelPath);                 }             }             else             {                 DataTable dtOneSheet = dt.Clone();                 int order = 1;                 for (int i = 0; i < dt.Rows.Count; i++)                 {                     dtOneSheet.ImportRow(dt.Rows[i]);

if (i > 0 && ((i + 1) == dt.Rows.Count || (i + 1) % 1000000 == 0))                     {                         excelPath = Kit.CreateExcel(dtOneSheet, FileName + "_" + order.ToString(), path, columns);                         order = order + 1;                         if (excelPath != "")                         {                             filelist.Add(excelPath);                         }                         dtOneSheet.Clear();                     }                 }                 IsZip = "2";             }

string Date = DateTime.Now.ToString("yyyyMMddHH");

if (IsZip == "0")             {                 FileStream excelFile = new FileStream(excelPath, FileMode.Open);//实例化一个FileStream对象                 byte[] byData = new byte[excelFile.Length];//建立一个FileStream要用的字节组                 excelFile.Read(byData, 0, byData.Length);                 excelFile.Dispose();                 File.Delete(excelPath);

HttpResponse resp;                 resp = HttpContext.Current.Response;                 resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

resp.AppendHeader("Content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlPathEncode(FileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".xlsx"));

resp.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

resp.BinaryWrite(byData);                 resp.End();             }             if (IsZip == "1" || IsZip == "2")             {                 string downFileName = FileName + DateTime.Now.ToString("yyyyMMddHHmmsss") + ".zip";                 string filename = path + "Code\\ZipExcel\\" + FileName + Date + ".zip";                 CreateZip(path + "Code\\ZipExcel\\", filename, filelist);

FileStream excelFile = new FileStream(filename, FileMode.Open);//实例化一个FileStream对象                 byte[] byData = new byte[excelFile.Length];//建立一个FileStream要用的字节组                 excelFile.Read(byData, 0, byData.Length);                 excelFile.Dispose();

File.Delete(filename);                 for (int count = 0; count < filelist.Count; count++)                 {                     File.Delete(filelist[count].ToString());                 }

HttpResponse resp;                 resp = HttpContext.Current.Response;                 resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

resp.AppendHeader("Content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlPathEncode(downFileName));

resp.ContentType = "application/zip";

resp.BinaryWrite(byData);                 resp.End();

}

}

DataTableToExcel的更多相关文章

  1. .NET基础架构方法—DataTableToExcel通用方法

    p { display: block; margin: 3px 0 0 0; } --> .NET架构基础方法—DataTableToExcel通用方法(NPOI) 今天封装DataTaleTo ...

  2. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  3. Aspose.Cells导出Excel(1)

    利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...

  4. DataTable to Excel(使用NPOI、EPPlus将数据表中的数据读取到excel格式内存中)

    /// <summary> /// DataTable to Excel(将数据表中的数据读取到excel格式内存中) /// </summary> /// <param ...

  5. C# WinForm 导出导入Excel/Doc 完整实例教程[使用Aspose.Cells.dll]

    [csharp] view plain copy 1.添加引用: Aspose.Cells.dll(我们就叫工具包吧,可以从网上下载.关于它的操作我在“Aspose.Cells操作说明 中文版 下载 ...

  6. 使用NPOI读取Excel到DataTable

    一.NPOI介绍: 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在POI 3.x版本之上的,它可以在没有安装Office ...

  7. .NET导入导出Excel方法总结

    最近,应项目的需求,需要实现Excel的导入导出功能,对于Web架构的Excel导入导出功能,比较传统的实现方式是: 1)导入Excel:将Excel文件上传到服务器的某一文件夹下,然后在服务端完成E ...

  8. 分享一个前辈的NPOIhelper

    即拿即用: 首先要下载npoi的dll,此不赘述,接着添加引用: using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel ...

  9. 利用npoi导出Excel

    npoi库是当下最流行的处理Excel.Word.PPT等Office文件格式 npoi的下载地址:http://npoi.codeplex.com/ npoi的官方学习地址: http://www. ...

随机推荐

  1. [转]使用maven镜像

    综述 用maven做项目,最郁闷的莫过于某些依赖库下载不了.被墙了,你懂的.使用maven镜像仓库及其重要,特别是国内的镜像,可以有效缓解被墙疼痛. 常用的镜像 国外镜像 ibiblio.org &l ...

  2. 走进AngularJs(七) 过滤器(filter) - 吕大豹

    时间 2013-12-15 16:22:00  博客园-原创精华区 原文  http://www.cnblogs.com/lvdabao/p/3475426.html 主题 AngularJS 过滤器 ...

  3. Problem A CodeForces 556A

    Description Andrewid the Android is a galaxy-famous detective. In his free time he likes to think ab ...

  4. MainActivity获取fragment控件button监听报空指针错误

    原因是是新版SDK创建项目时默认引入的fragment.xml,我的button是定义在fragment.xml里面的,而findviewbyid却是在main.activity里面调用的,而这样是获 ...

  5. Cisco IOS basic system management command reference

    absolute : to specify an absolute time for a time-range (in time-range configuration mode) no absolu ...

  6. [转]Putty中文乱码解决方法

    from: http://www.putty.ws/putty-luanma putty使用的过程中,你是否遇到过putty出现中文乱码的情况呢?putty终端出现乱码,是情况,多数是由于系统或软件缺 ...

  7. xlistview的java(脚)

    package com.bwie.xlistviews; import com.bwie.test.R; import android.content.Context;import android.u ...

  8. sql server2014各版本对比(连接)

    简单的说,sql server 2014为企业版(全功能).BI版.标准版. SQL Server 2014 各个版本支持的功能 http://msdn.microsoft.com/zh-cn/lib ...

  9. CDH上执行WordCount的意外和收获

    前面将Cloudera Manager安装到集群上的一台主机后,并通过Cloudera manager安装了hadoop-2.6.0-CDH5.4.4.今日来测试安装的集群是否很够很好的执行mapre ...

  10. html练习——个人简介

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...