本文介绍了如何更快地将Griddata导出到Excel。如果我有5000个记录,那么长时间出口。我想更快地导出数据..的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Satham.DataAccess1;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
namespace exptoexl
{
public partial class Form1 : Form
{
DataTable dt = new DataTable();
DBAccess db = new DBAccess();
public Form1()
{
InitializeComponent();
}
private void btnload_Click(object sender, EventArgs e)
{
//DataRow dr = dt.NewRow();
// dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
string sSql = "SELECT * FROM `fxwalkincustomer`";
db.ExecuteNonQuery(sSql);
dt = db.GetDataTable(sSql);
dataGridView1.DataSource = dt;
MessageBox.Show("Loading Complete");
}
private void btnexport_Click(object sender, EventArgs e)
{
load.InitialDirectory = "C:";
load.Title = "save as ExcelFile";
load.FileName = "";
load.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx|Excel Workbook|*.xlsx";
if (load.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = false;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
app.Columns.ColumnWidth = 20;
worksheet.Name = "Exported from dtaaGridView1";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
app.ActiveWorkbook.SaveCopyAs(load.FileName.ToString());
app.ActiveWorkbook.Saved = true;
app.Quit();
}
}
}
}
推荐答案
gv.DataSource = dt;
gv.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + yourfilename);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
这篇关于如何更快地将Griddata导出到Excel。如果我有5000个记录,那么长时间出口。我想更快地导出数据..的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!