以下代码现在正在运行,但是在打开Excel后我想要XLSX格式而没有任何损坏消息。
protected void BTNExportExcel_Click(object sender, EventArgs e)
{
DataTable dtexp= ExportTrends(); //const
try
{
Response.Clear();
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=Export.xls");
TextWriter tw = new StringWriter();
HtmlTextWriter h = new HtmlTextWriter(tw);
string[] images = TXTImages.Text.Split(new string[]{"<img"},StringSplitOptions.None);
if (images.Length > 0)
{
Response.Write(images[0].ToString());
for (int i = 1; i < images.Length; i++)
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string secondpart = images[i].Substring(images[i].IndexOf(',')+1);
img.ImageUrl = LoadImage(images[i].Substring(images[i].IndexOf(',') + 1, secondpart.LastIndexOf('\'')));
img.RenderControl(new HtmlTextWriter(Response.Output));
Response.Write("<BR/><BR/><BR/><BR/><BR/><BR/><BR/><BR/><BR/><BR/><BR/><BR/>");
}
}
Response.Write("<BR/>");
////// Create a dynamic control, populate and render it
GridView excel = new GridView();
excel.DataSource = dtexp;
excel.DataBind();
excel.RenderControl(new HtmlTextWriter(Response.Output));
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(string.Empty);
Response.Flush();
Response.End();
}
}
答案 0 :(得分:0)
确保您设置了对Excel的引用,然后下面的代码示例应该为您完成工作。
private void button1_Click(object sender, EventArgs e)
{
//connect with database
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = @"Provider=""Microsoft.Jet.OLEDB.4.0"";Data Source=""demo.mdb"";User Id=;Password=";
OleDbCommand command = new OleDbCommand();
command.CommandText = "select * from parts where Cost<1000 and ListPrice>500";
DataSet dataSet = new System.Data.DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command.CommandText, connection);
dataAdapter.Fill(dataSet);
DataTable dt = dataSet.Tables[0];
this.dataGridView1.DataSource = dt;
//export specific data to Excel
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets[0];
book.Worksheets[0].InsertDataTable(this.dataGridView1.DataSource as DataTable, true, 1, 1);
book.SaveToFile("sample.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("sample.xlsx");
}