asp.net实现的excel下载,下载的文件打开后为什么还有一个"Book2"
asp.net实现的excel下载,下载的文件打开后为什么还有一个"Book2"的文件,并且这个文件的内容才是我要的,默认的那个内容不正确!(比如说我下载一个学生信息到excel,里面有25条记录,我打开这个文件,它里面只有2条记录,并且为不正确的数据,但它还会有一个“Book2”文件,里面有25条记录,且完全正确!请教大虾~~这是怎么回事?) --------------------编程问答-------------------- 无代码无易做图... --------------------编程问答--------------------
--------------------编程问答-------------------- 下面是我用的生成excel文件的方法:
using System;
using System.IO;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Globalization;
using System.Collections;
namespace jxoa.Core
{
/// <summary>
/// ExcelHelper 的摘要说明。
/// </summary>
public class ExcelHelper
{
#region Fields
string _fileName;
DataTable _dataSource;
string[] _titles = null;
string[] _fields = null;
int _maxRecords = 100000;
#endregion
#region Properties
/// <summary>
/// 限制输出到 Excel 的最大记录数。超出则抛出异常
/// </summary>
public int MaxRecords
{
set { _maxRecords = value; }
get { return _maxRecords; }
}
/// <summary>
/// 输出到浏览器的 Excel 文件名
/// </summary>
public string FileName
{
set { _fileName = value; }
get { return _fileName; }
}
#endregion
/// <summary>
/// 空构造函数
/// </summary>
public ExcelHelper()
{
}
#endregion
#region public Methods
/// <summary>
/// 导出到 Excel 并提示下载
/// </summary>
/// <param name="dg">DataGrid</param>
public void Export(DataGrid dg) //这里的参数。自己定义。如gridview,datalist
{
if (dg == null)
throw new ArgumentNullException("dg");
if (dg.AllowPaging || dg.PageCount > 1)
throw new ArgumentException("paged DataGrid can't be exported.", "dg");
// 添加标题样式
dg.HeaderStyle.Font.Bold = true;
dg.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
RenderExcel(dg);
}
private void RenderExcel(Control c)
{
// 确保有一个合法的输出文件名 上面 _fileName 定义的属性
if (_fileName == null || _fileName == string.Empty || !(_fileName.ToLower().EndsWith(".xls")))
_fileName = GetRandomFileName();
HttpResponse response = HttpContext.Current.Response;
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = "application/ms-excel/msword";
response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName));
CultureInfo cult = new CultureInfo("zh-CN", true);
StringWriter sw = new StringWriter(cult);
HtmlTextWriter writer = new HtmlTextWriter(sw);
writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=GB2312\">");
DataGrid dg = c as DataGrid; //这里根据你上面定义的来 如gridview,datalist
if (dg != null)
{
dg.RenderControl(writer);
}
c.Dispose();
response.Write(sw.ToString());
response.End();
}
/// <summary>
/// 得到一个随意的文件名
/// </summary>
/// <returns></returns>
private string GetRandomFileName()
{
Random rnd = new Random((int) (DateTime.Now.Ticks));
string s = rnd.Next(Int32.MaxValue).ToString();
return DateTime.Now.ToShortDateString() + "_" + s + ".xls";
}
}
}
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="fileName"></param>
/// <param name="cloNames"></param>
/// <param name="templetFilePath"></param>
public static void ExportToExcel(DataTable dt, string fileName, string[] cloNames, string templetFilePath)
{
try
{
object missing = Missing.Value;
Excel.Application app;
Excel.Workbook workBook;
Excel.Worksheet workSheet;
Excel.Range range;
//创建一个Application对象并使其不可见
app = new Excel.ApplicationClass();
app.Visible = false;
//创建一个WorkBook对象
workBook = app.Workbooks.Add(missing);
//得到WorkSheet对象
workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
int rowCount = dt.Rows.Count + 1; //DataTable行数+第一列
int colCount = dt.Columns.Count; //DataTable列数
//利用二维数组批量写入
string[,] arr = new string[rowCount, colCount];
for (int j = 0; j < rowCount; j++)
{
for (int k = 0; k < colCount; k++)
{
if (j == 0)
{
arr[j, k] = cloNames[k];
}
else
{
arr[j, k] = dt.Rows[j - 1][k].ToString();
}
}
}
range = (Excel.Range)workSheet.Cells[1, 1]; //写入Exel的坐标
range = range.get_Resize(rowCount, colCount);
range.Value2 = arr;
workBook.SaveAs(templetFilePath + fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
if (workBook.Saved)
{
workBook.Close(null, null, null);
app.Workbooks.Close();
app.Quit();
}
if (range != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
range = null;
}
if (workSheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
workSheet = null;
}
if (workBook != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
workBook = null;
}
if (app != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
GC.Collect();//强制代码垃圾回收
//下载文件
}
catch (Exception e)
{
}
}
补充:.NET技术 , ASP.NET