数据原共400条数据,21列,我是双核cpu,4G内存
1. Excel com组件
要3秒左右,上千条30秒+这种方法比较慢,要引用Microsoft.Office.Interop.Excel

#region DataSet导入到Excel里(最原始样式)
/// <summary>
/// DataSet导入到Excel里,多个DataTable分成多个Sheet,Sheet名以TableName命名
/// </summary>
/// <param name="DS">要导入的Excel</param>
/// <param name="FilePathAndName">要保存的路径和文件名(绝对路径)</param>
public static void DataSetToExcel(DataSet DS, string FilePathAndName)
{
string strName = FilePathAndName.Replace(@"\\", @"\").Replace(@"\\", @"\").Replace(@"\\", @"\");
strName = FilePathAndName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
try
{
excel.Visible = false;
//设置禁止弹出保存和覆盖的询问提示框
excel.DisplayAlerts = false;
excel.AlertBeforeOverwriting = false;
//增加一个工作簿
Microsoft.Office.Interop.Excel.Workbook book = excel.Workbooks.Add(true);
System.Reflection.Missing miss = System.Reflection.Missing.Value;
//添加工作表
Microsoft.Office.Interop.Excel.Worksheet sheets = (Microsoft.Office.Interop.Excel.Worksheet)
book.Worksheets.Add(miss, miss, , Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
for (int i = ; i < DS.Tables.Count; i++)
{
System.Data.DataTable table = DS.Tables[i];
//获取一个工作表
//Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets[i + 1] as Microsoft.Office.Interop.Excel.Worksheet; Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets.Add(book.Worksheets[i + ], Type.Missing, Type.Missing, Type.Missing) as Microsoft.Office.Interop.Excel.Worksheet;
int rowIndex = ;
int colIndex = ;
foreach (DataColumn col in table.Columns)
{
colIndex++;
sheet.Cells[, colIndex] = col.ColumnName;
Microsoft.Office.Interop.Excel.Range Range1 = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[, colIndex];
Range1.Font.Bold = true;//表头字体加粗
Range1.Borders.Value = ;
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = ;
foreach (DataColumn col in table.Columns)
{
colIndex++;
sheet.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
//sheet.Name = tableNames[i];
sheet.Name = GetLegalFileName(DS.Tables[i].TableName.ToString());
}
//删除多余Sheet
for (int g = ; g <= book.Worksheets.Count; g++)
{
Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets[g] as Microsoft.Office.Interop.Excel.Worksheet; if (sheet.Name.Length > && sheet.Name.Substring(, ) == "Sheet")
{
sheet.Delete();
g--;
}
}
//book.Save();
book.SaveAs(strName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
book.Close(false, miss, miss);
book = null;
}
catch (Exception)
{
throw;
}
finally
{
KillExcelProcess(excel);//结束Excel进程
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
#endregion

2. OLEDB

这个需要3秒左右,要using System.Data.OleDb;

#region oledb方式
public static void ExcelExport(DataTable dt, string filepath, string tablename)
{
//excel 2003格式
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
//Excel 2007格式
//string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0 Xml;";
try
{
using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
StringBuilder strSQL = new StringBuilder();
strSQL.Append("CREATE TABLE ").Append("[" + tablename + "]");
strSQL.Append("(");
for (int i = ; i < dt.Columns.Count; i++)
{
strSQL.Append("[" + dt.Columns[i].ColumnName + "] text,");
}
strSQL = strSQL.Remove(strSQL.Length - , );
strSQL.Append(")"); OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con);
cmd.ExecuteNonQuery(); for (int i = ; i < dt.Rows.Count; i++)
{
strSQL.Clear();
StringBuilder strfield = new StringBuilder();
StringBuilder strvalue = new StringBuilder();
for (int j = ; j < dt.Columns.Count; j++)
{
strfield.Append("[" + dt.Columns[j].ColumnName + "]");
strvalue.Append("'" + dt.Rows[i][j].ToString() + "'");
if (j != dt.Columns.Count - )
{
strfield.Append(",");
strvalue.Append(",");
}
else
{
}
}
cmd.CommandText = strSQL.Append(" insert into [" + tablename + "]( ")
.Append(strfield.ToString())
.Append(") values (").Append(strvalue).Append(")").ToString();
cmd.ExecuteNonQuery();
}
con.Close();
}
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

3.NPOI
 这个在有二种方式,第一种在web页面下,很快,秒的速度,但是下下来的方式没有保存在某一目录下

aspx页只有一个按钮就可以了,.cs文件代码如下

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel; namespace ExportXlsToDownload
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void Button1_Click(object sender, EventArgs e)
{
string filename="test.xls";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",filename));
Response.Clear(); InitializeWorkbook();
GenerateData();
GetExcelStream().WriteTo(Response.OutputStream);
Response.End();
} HSSFWorkbook hssfworkbook; MemoryStream GetExcelStream()
{
//Write the stream data of workbook to the root directory
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
return file;
} void GenerateData()
{
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); sheet1.CreateRow().CreateCell().SetCellValue("This is a Sample");
int x = ;
for (int i = ; i <= ; i++)
{
IRow row = sheet1.CreateRow(i);
for (int j = ; j < ; j++)
{
row.CreateCell(j).SetCellValue(x++);
}
}
} void InitializeWorkbook()
{
hssfworkbook = new HSSFWorkbook(); ////create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi; ////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
}
}
}

第二种方式,可以保存在目录下,也是秒存,代码如下

    public class NPOIExcel
{
//最大数据条数
readonly int EXCEL03_MaxRow = ; /// <summary>
/// 将DataTable转换为excel2003格式。
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public byte[] DataTable2Excel(DataTable dt, string sheetName)
{ IWorkbook book = new HSSFWorkbook();
if (dt.Rows.Count < EXCEL03_MaxRow)
DataWrite2Sheet(dt, , dt.Rows.Count - , book, sheetName);
else
{
int page = dt.Rows.Count / EXCEL03_MaxRow;
for (int i = ; i < page; i++)
{
int start = i * EXCEL03_MaxRow;
int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - ;
DataWrite2Sheet(dt, start, end, book, sheetName + i.ToString());
}
int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow;
DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, lastPageItemCount, book, sheetName + page.ToString());
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
return ms.ToArray();
}
private void DataWrite2Sheet(DataTable dt, int startRow, int endRow, IWorkbook book, string sheetName)
{
ISheet sheet = book.CreateSheet(sheetName);
IRow header = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = header.CreateCell(i);
string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName;
cell.SetCellValue(val);
}
int rowIndex = ;
for (int i = startRow; i <= endRow; i++)
{
DataRow dtRow = dt.Rows[i];
IRow excelRow = sheet.CreateRow(rowIndex++);
for (int j = ; j < dtRow.ItemArray.Length; j++)
{
excelRow.CreateCell(j).SetCellValue(dtRow[j].ToString());
}
} }
}

第二种方式调用如下:

DataTable dt=GetData();
NPOIExcel myhelper = new NPOIExcel();
byte[] data = myhelper.DataTable2Excel(dt,"sheet");
string path = "d:\\temp" + DateTime.Now.Ticks.ToString() + ".xls";
if (!File.Exists(path))
{
FileStream fs = new FileStream(path, FileMode.CreateNew);
fs.Write(data, , data.Length);
fs.Close(); }

.net导出Excel几种方式比较的更多相关文章

  1. 关于poi导出excel三种方式HSSFWorkbook,SXSSFWorkbook,csv的总结

    poi导出excel最常用的是第一种方式HSSFWorkbook,不过这种方式数据量大的话会产生内存溢出问题,SXSSFWorkbook是一种大数据量导出格式,csv是另一种excel导出的一种轻快的 ...

  2. js 实现纯前端将数据导出excel两种方式,亲测有效

    由于项目需要,需要在不调用后台接口的情况下,将json数据导出到excel表格,兼容chrome没问题,其他还没有测试过 通过将json遍历进行字符串拼接,将字符串输出到csv文件,输出的文件不会再是 ...

  3. Hive数据导入导出的几种方式

    一,Hive数据导入的几种方式 首先列出讲述下面几种导入方式的数据和hive表. 导入: 本地文件导入到Hive表: Hive表导入到Hive表; HDFS文件导入到Hive表; 创建表的过程中从其他 ...

  4. Hive创建表|数据的导入|数据导出的几种方式

    * Hive创建表的三种方式 1.使用create命令创建一个新表 例如:create table if not exists db_web_data.track_log(字段) partitione ...

  5. Excel导出的几种方式

    1.html 前台html与js代码(文件:ExportExcelByHtml.aspx): <html xmlns="http://www.w3.org/1999/xhtml&quo ...

  6. Hive数据导入导出的n种方式

    Tutorial-LoadingData Hive加载数据的6种方式 #格式 load data [local] inpath '/op/datas/xxx.txt' [overwrite] into ...

  7. excel导入导出的两种方式:csv和XLS

    依赖 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl ...

  8. C++ DLL导出的两种方式和链接的两种方式

    第一种 导出方式 extern "C" _declspec(dllexport) int Plus(int x, int y); extern "C" _dec ...

  9. Hive数据导出的几种方式

    在hive的日常使用中,经常需要将hive表中的数据导出来,虽然hive提供了多种导出方式,但是面对不同的数据量.不同的需求,如果随意就使用某种导出方式,可能会导致导出时间过长,导出的结果不满足需求, ...

随机推荐

  1. LOJ2721 [NOI2018] 屠龙勇士 【扩展中国剩余定理】

    好久没写了,写一篇凑个数. 题目分析: 这题不难想,讲一下中国剩余定理怎么扩展. 考虑$$\left\{\begin{matrix}x \equiv a\pmod{b}\\ x \equiv c\pm ...

  2. MT【291】2元非齐次不等式

    实数$x,y$满足$x^2+y^2=20,$求$xy+8x+y$的最大值___ 法一:$xy\le\dfrac{1}{4}x^2+y^2,8x\le x^2+16,y\le\dfrac{1}{4}y^ ...

  3. 【UOJ#311】【UNR #2】积劳成疾(动态规划)

    [UOJ#311][UNR #2]积劳成疾(动态规划) UOJ Solution 考虑最大值分治解决问题.每次枚举最大值所在的位置,强制不能跨过最大值,左右此时不会影响,可以分开考虑. 那么设\(f[ ...

  4. [SNOI2017]一个简单的询问【莫队+容斥原理】

    题目大意 给你一个数列,让你求两个区间内各个数出现次数的乘积的和. 分析 数据范围告诉我们可以用莫队过. 我并不知道什么曼哈顿什么乱七八糟的东西,但是我们可以用容斥原理将这个式子展开来. \[\sum ...

  5. [2017-7-26]Android Learning Day4

    RecycleView 恩,学习Fragment的过程中的一个小实践居然用到了RecycleView!坑了我好久有木有!!好气哦,从昨晚到现在.(现在也还是一头雾水,不过照搬也会用了) 这是第一版的代 ...

  6. 协同过滤算法 teamCF

    http://www.infoq.com/cn/articles/recommendation-algorithm-overview-part02

  7. 课后选做题:MyOD

    目录 OD命令了解 MyOD实现 OD命令了解 作用:od命令用于输出文件的八进制.十六进制或其它格式编码的字节,通常用于显示或查看文件中不能直接显示在终端的字符.常见的文件为文本文件和二进制文件.此 ...

  8. bzoj3467: Crash和陶陶的游戏

    就一篇题解: BZOJ3467 : Crash和陶陶的游戏 - weixin_34248487的博客 - CSDN博客 1.离线,建出Atrie树:B树的倍增哈希数组,节点按照到根路径字典序排序 2. ...

  9. A1017. Queueing at Bank

    Suppose a bank has K windows open for service. There is a yellow line in front of the windows which ...

  10. centos7安装saltstack

    环境是Cenos7 saltstack-master:192.168.0.140 saltstack-minion:192.168.0.141 安装epel yum源 yum -y install e ...