您的位置:首页 > 其它

用excel组件生成excel报表

2011-03-25 09:52 411 查看
protected void Button4_Click(object sender, EventArgs e)
{
string temp = this.Request["val_a"];
string[] content = Regex.Split(temp, @"/^/^");
string jh = content[0].Replace("'", "''").Trim();
string bh = content[1].Replace("'", "''").Trim();
string cyrq= content[2].Replace("'", "''").Trim();
XMU.Data.DataAccess dp = new XMU.Data.DataAccess();
try
{
string sql = "select * from YBG where jh='" + jh + "' and bh ='" + bh + "' and cyrq='" + cyrq + "' ";
DataSet ds_data = dp.GetList(sql);
DataTable dt = ds_data.Tables[0];
if (ds_data.Tables[0].Rows.Count != 0)
{
string rq = DateTime.Now.DayOfWeek.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
string path1 = Request.PhysicalApplicationPath + @"input/file/ybaobiao1.xls";
string path = Request.PhysicalApplicationPath + @"input/file/ybaobiao1" + rq + ".xls";
System.IO.File.Copy(path1, path, true);//copy一份,以缓解内存压力。访问时,一人一份
object oMissing =System.Reflection.Missing.Value;
Excel.ApplicationClass App = new Excel.ApplicationClass();//建立了一个新的Excel实例
Excel.Workbook ew = App.Workbooks.Open(path,oMissing,oMissing,oMissing, //创建excel 对象,打开path下的文件
oMissing,oMissing,oMissing,
oMissing,oMissing,oMissing,
oMissing,oMissing,oMissing,oMissing,oMissing);

Excel.Worksheet xlSheet = null; //创建一个工作表区
xlSheet = (Excel.Worksheet)ew.Worksheets[1];//得到excel里面的第一个sheet 第2个就是Worksheets[2];

((Excel.Range)xlSheet.Cells[3, 2]).Value2= dt.Rows[0]["JH"].ToString();//获得第几行,第几列的值
((Excel.Range)xlSheet.Cells[3, 4]).Value2 = dt.Rows[0]["CW"].ToString();
((Excel.Range)xlSheet.Cells[3, 6]).Value2 = dt.Rows[0]["JDSD"].ToString();
................

................

................

................

ew.Save();
//ew.SaveAs(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

//关闭excel进程
System.Runtime.InteropServices.Marshal.ReleaseComObject(ew);//释放excel对象
ew = null;

App.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(App);//释放excel实例
App = null;

GC.Collect();
System.IO.FileInfo fi = new System.IO.FileInfo(path);//在指定的模式中打开文件
Page.Response.Clear(); //清除缓冲区流中的所有内容输出
Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Page.Response.Charset = "utf-7";
Page.Response.AppendHeader("Content-Disposition", "attachment; filename=/"" + HttpUtility.UrlEncode("油报告.xls") + "/"");
Page.Response.AppendHeader("Content-Length", fi.Length.ToString());
Page.Response.ContentType = "application/octet-stream";
Page.Response.WriteFile(path);
Page.Response.End();
}
}
finally
{
dp.Close();
}

this.Bind_Data();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: