private void ExeclOut(DataTable dt,string filePath)
{
Excel.Application myExcel = new Excel.ApplicationClass();
try
{
object missing = System.Reflection.Missing.Value;
Excel._Workbook xBk ; //工作薄
Excel._Worksheet xSt; //工作Sheet
xBk = myExcel.Workbooks.Add(true);
xSt = (Excel._Worksheet)xBk.ActiveSheet;
xSt.Name ="Sheet1";
for(int i=0;i
for (int j=1;j
myExcel.Cells[i+2,j] = dt.Rows[i][j];
}
}
myExcel.Sheets.Add(missing,missing,1,Excel.XlSheetType.xlWorksheet);
string SaveUml = filePath;
myExcel.Visible = true;
if (File.Exists(SaveUml))
System.IO.File.Delete(SaveUml);
xBk.SaveAs(SaveUml,missing,missing,
missing,missing,missing,Excel.XlSaveAsAccessMode.xlShared,
missing,missing,missing,missing,missing);
//myExcel.Save(@"d:cms.xls");
myExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
GC.Collect();
}
catch
{
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
GC.Collect();
Response.Write("");
}
finally
{
//释放ExcelCOM资源,必须执行,否则EXECL进程不会自动释放
System.Runtime.InteropServices.Marshal.ReleaseComObject((object)myExcel);
GC.Collect();
}
}
private void DownFile(string pathfile)
{
if (pathfile != "")
{
//下面这段代码从网络上得到
FileStream fs = new FileStream(pathfile, FileMode.Open, FileAccess.Read); //用只读方式打开文件
long p = 0;
FileInfo fi = new FileInfo(pathfile); //得到文件信息
long l = fi.Length; //得到文件大小
if (Request.Headers["Range"] != null)
{
Response.StatusCode = 206;
p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
}
//根据http请求做出相应的回答
Response.AddHeader("Content-Length", ((long)(l - p)).ToString());
if (p != 0)
{
Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(l - p)).ToString() + "/" + l.ToString());
}
//返回一些http头信息
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(pathfile));
//返回一些http头信息
fs.Position = p;
int i = 1;
byte[] b = new Byte[1024];
while (i > 0)
{
i = fs.Read(b, 0, b.Length);
Response.OutputStream.Write(b, 0, i);
}
//返回文件的内容
fs.Close(); //关闭文件
Response.End(); //http回应结束
}
}
以上的方法受到操作系统和OFFICE版本的限制,我在网上找一个高手写好DLL,里面有方法可以十分方便的保存和导出EXECL,相当的方便啊,DLL见附件,里面有附带使用方法。
附件下载
另外,我发现上的文件下载经常会出现问题,具体怎么引起的我也不清楚,所以还使用最普通的方法吧
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(pathfile));
Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.WriteFile(pathfile); // 把文件流发送到客户端
Response.End();
其实哪个DLL中还有很多关于EXECL的方法,不够我现在没有必要去研究他,如果有需要的人可以反编译下,我试过了,可以反编译成正常运行的执行项目,另外提下,这个DLL不能使用在VS2003中,好象不能识别出来。