c#生成Excel文件在服务器并且可以导出到本地
许多导出Excel都是导出到本地,而很多时候我们都要生成到服务器上。
好,不多说,先把代码贴出来先.
首先在头部要using
using System.IO;
using System.Text;
using System.Data;
using MSExcel=Microsoft.Office.Interop.Excel;
using System.Reflection;
如果没有把Excel的dll文件引用进来,首先要引用。在右键添加引用后选择.net里面就能找到了。
接下来,先给出导出到本地的代码,
首先要重写一个方法:
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}
然后在摸个按钮事件,或者写成个方法生成Excel文件到本地:
protected void ButtonToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = false;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=MyExcel.xls"); //文件名为MyExcel
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //编码格式
Response.ContentType = "application/ms-excel";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
GridViewExcel.RenderControl(oHtmlTextWriter); //GridViewExcel为GridView的ID
Response.Write(oStringWriter.ToString());
Response.End();
}
好,接下来贴出生成到服务器的代码:
private void CreateExcel()
{
object path;
MSExcel.Application excelApp;
MSExcel.Workbook excelDoc;
path = Server.MapPath("~/MyExcel.xls");//在服务的根文件夹下生成MyExcel.xls文件
excelApp = new MSExcel.ApplicationClass();
if (File.Exists((string)path))
{
File.Delete((string)path);//判断是否存在,如果存在就删掉。
}
Object Nothing = Missing.Value;
excelDoc = excelApp.Workbooks.Add(Nothing);
MSExcel.Worksheet MyWorkSheet = (MSExcel.Worksheet)excelDoc.Worksheets[1];
MyWorkSheet.get_Range("A1", System.Type.Missing).Value2 = "技术";
MyWorkSheet.get_Range("B1", System.Type.Missing).Value2 = "掌握程度";//这里是内容,按Excel里面的格式填就好了。
object format = MSExcel.XlFileFormat.xlWorkbookDefault;
excelDoc.SaveAs(path, Nothing, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
excelDoc.Close(Nothing, Nothing, Nothing);
excelApp.Quit();
}