2024年1月5日发(作者:)
C#导出Excel速度慢的解决方法
方法一:
通过二维数组把数据准备好,一次性写入Excel:
private ation excelApp= new ationClass();
private ok excelBook = (g);
private eet excelSheet = (eet)Sheet;
e = true;
public void DataTableToExcel(DataTable dt)
{
int rowCount = ;
int colCount = ;
object[,] dataArray = new object[rowCount,colCount];
for (int i = 0; i < rowCount; i++)
{
for (int j=0;j< colCount;j++)
{
dataArray[i, j] = [i][j];
}
}
_Range("A1", [rowCount, colCount]).Value2 =
dataArray;
}
由于二维数组是在内存中实现,所以速度很快,由于是一次性写入到Excel中,使我们几乎感觉不到延迟,在Excel打开后数据马上就出来了,感觉很爽。
方法二:
private void SaveAs() //另存新档按钮,导出成Excel
{
DataTable dt = le("select * from table");
if ( == 0)
{
("没有要输出为excel的数据!");
return;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
= "Execl files (*.xls)|*.xls";
Index = 0;
eDirectory = true;
Prompt = true;
= "生成Excel";
alog();
Stream myStream;
try
{
myStream = le();
//StreamWriter sw = new StreamWriter(myStream, oding("gb2312"));
StreamWriter sw = new StreamWriter(myStream, oding(-0));
try
{
string str = "字段t字段t字段t";//表头
ine(str);
for (int i = 0; i < ; i++)
{
string tempStr = ;
tempStr += [i]["a"].ToString() + "t";
tempStr += [i]["b"].ToString() + "t";
tempStr += [i]["c"].ToString() + "t";
ine(tempStr);
}
//("导出成功!");
}
catch (Exception e)
{
();
(ng());
}
finally
{
();
();
}
();
();
}
catch (Exception e)
{
(e);
return;
}
}
方法三:
using System;
using ;
using uration;
using tions;
using ;
using ty;
using ;
using trols;
using ts;
using ntrols;
using g;
using ;
using ;
///
/// Author:匆匆 Blog:/huangjianhuakarl/
/// 将Gridview中的数据导出Excel表格
///
public partial class GridviewExcel :
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
///
/// 数据绑定
///
public void bind()
{
string sqlStr = "select * from Employee";
DataSet myds = t(sqlStr);
urce = myds;
yNames = new string[] { "ID" };
nd();
}
///
/// 在GridView 控件中的某个行被绑定到一个数据记录时发生。此事件通常用于在某个行被绑定到数据时修改该行的内容。
///
///
///
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (TableCell tc in )
{
utes["style"] = "border-color:Black";
}
if (ex != -1)
{
int id = dex * ze + ex + 1;
[0].Text = ng();
}
}
///
/// 导出Excel
///
///
///
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "Employee ");
}
///
/// 定义导出Excel的函数
///
///
///
private void Export(string FileType, string FileName)
{
t = "GB2312";
tEncoding = 8;
Header("Content-Disposition", "attachment;filename=" + ode(FileName, 8).ToString());
tType = FileType;
ViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
Control(hw);
(ng());
();
}
///
/// 此方法必重写,否则会出错
///
///
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
//Export("application/ms-excel", "");
Export("application/ms-word", "员工信息.doc");//都可以
}
}
网页源码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="" Inherits="GridviewExcel" EnableEventValidation="false" %>
发布评论