因為工作上的需求,要可以輸出Excel 或 Ods 所以寫了這個做紀錄!!
Excel 部份就不實作了,使用NPOI 或者 EPPLUS 很容易的。
使用套件: Microsoft.Office.Interop
作法:先做成Excel 後存實體路徑,在用 Microsoft.Office.Interop 轉存 Ods 後,在將其讀出存至 byte[] 最後輸出,刪除實體檔,收工。
直接看以下實作:
string guid = Guid.NewGuid().ToString();
string fileName = @"e:\" + guid + ".xls";
FileStream file = new FileStream(fileName, FileMode.Create);
wb.Write(file);
file.Close();
// 轉ods
var excelAPP = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook book = excelAPP.Workbooks.Open(fileName);
string odfPath = fileName.Replace("xls", "ods");
book.SaveAs(odfPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenDocumentSpreadsheet);
excelAPP.Visible = false;
excelAPP.Quit();
// 讀ods 寫入 FileStream
byte[] outPutFile = null;
using (FileStream fs = new FileStream(odfPath, FileMode.Open))
{
outPutFile = new byte[fs.Length];
fs.Read(outPutFile, 0, outPutFile.Length);
}
// 刪除xls
System.IO.File.Delete(fileName);
// 刪除ods
System.IO.File.Delete(odfPath);
return File(outPutFile, "application/vnd.oasis.opendocument.spreadsheet", odfPath);