using Microsoft.Office.Interop.Excel;
using System.IO;
protected void Button1_Click(object sender, EventArgs e)
{
string cao = HttpContext.Current.Server.MapPath("excel");//获取路径,获取的是当前文件夹的路径,加上excel后,路径会在之前的路径上加上excel。
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
if (app == null)
{
return;
}
app.Visible = false;
app.UserControl = true;
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(cao+"//cs.xls");//这里的Add方法里的参数就是模板的路径
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);//模板只有一个sheet表
if (worksheet == null)
{
return;
}
Common.Data.IDataProvider myProvider = Common.Frame.DataOper.GetSystemDataProvider();
System.Data.DataTable dt = myProvider.GetData("select xy_studyid,studentname,sex,linkphone from gongjiao_xy_newstudent where firstday=to_date('2010-4-1','yyyy-mm-dd')");
for (int i = 0; i < dt.Rows.Count; i++)
{
worksheet.Cells[i + 2, 1] = dt.Rows[i]["xy_studyid"].ToString();
worksheet.Cells[i + 2, 2] = dt.Rows[i]["studentname"].ToString();
worksheet.Cells[i + 2, 3] = dt.Rows[i]["sex"].ToString();
worksheet.Cells[i + 2, 4] = dt.Rows[i]["linkphone"].ToString();
}
string tick = DateTime.Now.Ticks.ToString();
string save_path = cao+"//" + tick + ".xls";//f://excel//" + tick + ".xls
object ms = Type.Missing;
workbook.SaveAs(save_path, ms, ms, ms, ms, ms, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, ms, ms, ms, ms, ms);
ExcelOperate eo = new ExcelOperate();
eo.Dispose(worksheet, workbook, app);
//------------------------------------------下面是弹出打开下载框的代码
FileInfo fi = new FileInfo(save_path);
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(save_path, System.Text.Encoding.UTF8));//save_path//Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(file_name, System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(fi.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
//ExcelOperate eo = new ExcelOperate();
eo.Dispose(worksheet, workbook, app);
//excelOperate.Dispose();//关闭Excel进程
}
//-----------------------------------------------
另附:
要想在excel中的一个单元格中换行显示
worksheet.Cells[i + 1, 1] = "姓名:" + GridView1.Rows[i].Cells[2].Text + "/n性别:" + GridView1.Rows[i].Cells[3].Text + "/n出生日期:" + GridView1.Rows[i].Cells[4].Text + "/n来本市日期:" + GridView1.Rows[i].Cells[6].Text + "/n场住户口所在地:" + GridView1.Rows[i].Cells[7].Text + "/n暂住地址:" + GridView1.Rows[i].Cells[8].Text + "/n身份证号:" + GridView1.Rows[i].Cells[5].Text + "/n有效期限:" + GridView1.Rows[i].Cells[9].Text + "/n编号:" + GridView1.Rows[i].Cells[10].Text;
在要换行的地方加上/n。