110,500
社区成员
发帖
与我相关
我的任务
分享
protected void Button3_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
FirstBindData(); ;
try
{
if (conn != null)
{
cmd.Dispose();
conn.Close();
}
//文件路径
String strFilePath = "\\excel\\";
String strFileName = DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
//判断是不是null
if (xlApp == null)
{
Response.Write("<script>alert('创建Excel失败!')</script>");
return;
}
Object ms = Type.Missing;
Microsoft.Office.Interop.Excel.Workbook myBook = xlApp.Workbooks.Add(ms);
Microsoft.Office.Interop.Excel.Worksheet mySheet = myBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
//自动调整列宽
mySheet.Columns.EntireColumn.ColumnWidth = 15;
for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[1].Columns.Count; j++)
{
mySheet.Cells[i + 2, j + 1] = ds.Tables[1].Rows[i][j].ToString();
}
}
if (System.IO.File.Exists(this.MapPath(".") + strFilePath + strFileName))
{
System.IO.File.Delete(this.MapPath(".") + strFilePath + strFileName);
}
String strXlsPath = this.MapPath(".") + strFilePath + strFileName;
myBook.SaveAs(strXlsPath, ms, ms, ms, ms, ms, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, ms, ms, ms, ms, ms);
xlApp.Quit();
System.IO.FileInfo file = new System.IO.FileInfo(strXlsPath);
Response.Clear();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(file.FullName);
;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception error)
{
Response.Write(error.ToString());
//释放Excel资源
xlApp.Quit();
if (conn != null)
{
cmd.Dispose();
conn.Close();
}
Response.Write("<script>alert('创建Excel失败!')</script>");
}
}