我有一个带有一些信息的文本文件,我使用EPPlus将其转换为ExcelPackage对象,现在我想知道是否有办法用excel打开这个对象而不将其保存到本地文件?如果不可能,我可以使用临时目录将其保存到文件中,然后打开它吗?
答案 0 :(得分:2)
如果您正在谈论Windows应用,您可以使用类似System.IO.Path.GetTempPath()
的内容。您可以从这里获得更多信息:
How to get temporary folder for current user
所以,像这样:
[TestMethod]
public void TempFolderTest()
{
var path = Path.Combine(Path.GetTempPath(), "temp.xlsx");
var tempfile = new FileInfo(path);
if (tempfile.Exists)
tempfile.Delete();
//Save the file
using (var pck = new ExcelPackage(tempfile))
{
var ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells[1, 2].Value = "Excel Test";
pck.Save();
}
//open the file
Process.Start(tempfile.FullName);
}
如果你在谈论网络,你不应该全部保存,只需通过回复发送:
using (ExcelPackage pck = new ExcelPackage())
{
var ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells[1, 2].Value = "Excel Test";
var fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename=\"{0}\"; size={1}; creation-date={2}; modification-date={2}; read-date={2}"
, "temp.xlsx"
, fileBytes.Length
, DateTime.Now.ToString("R"))
);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(fileBytes);
Response.End();
}