如何使用封闭的xml将创build的excel文件转换为字节格式

您好我使用的是用于导出到Excel的closedxML DLL我有如下所示的静态方法

public static void WriteToExcel(string fileName, List<CP> pages) { var wb = new XLWorkbook(); byte[] file; var ws = wb.Worksheets.Add("CPs"); WriteCostHeader(ws); ////write all the header columns //for (int i = 0; i < pages.Count; i++) int iRow = 2; foreach(var page in pages) { WriteCostPage(ws, page, iRow++); WriteCostItemHead(ws, iRow++); foreach(var item in page.Items) { WriteCostItem(ws, item, iRow++); } iRow++; } wb.SaveAs(fileName); } 

我在下面的方法中调用上面的函数

 public static List<CP> Init() { //binding items to to list } static void Main(string[] args) { byte[] file; file = ExcelProvider.WriteToExcel("D:\\Temp\\Test1.xls", Init()); //Console.WriteLine("done"); //Console.ReadLine(); } public byte[] CreatePackage() { string fileName = string.Format("{0}.xlsx", "Generated"); byte[] excelFile; // getting error here cannot convert void to byte[] excelFile = ExcelProvider.WriteToExcel(fileName, Init()); } 

但我需要得到的结果excel工作表的字节数,我需要将其存储在内存stream以后我可以用于进一步的目的..

但我不知道如何获得以字节格式创build的Excel文件…

请问任何人可以提供任何想法或解决scheme在这一个…非常感谢事先…

请这样做: –

 //Open the File into file stream FileStream fileStream = new FileStream(Server.MapPath(fileName), FileMode.Open, FileAccess.Read, FileShare.Read); //Create and populate a memorystream with the contents of the MemoryStream mstream = StreamToMemory(fileStream); // delete the file when it is been added to memory stream File.Delete(Server.MapPath(fileName)); //Convert the memorystream to an array of bytes. byte[] byteArray = mstream.ToArray(); //Clean up the memory stream mstream.Flush(); mstream.Close(); // Clear all content output from the buffer stream Response.Clear(); // Add a HTTP header to the output stream that specifies the default filename // for the browser's download dialog Response.AddHeader("Content-Disposition", "attachment; filename=QatargasTimesheet-" + ((DateTime)rdDate.SelectedDate).ToString("MMM yyyy") + ".xls"); // Add a HTTP header to the output stream that contains the // content length(File Size). This lets the browser know how much data is being transfered Response.AddHeader("Content-Length", byteArray.Length.ToString()); // Set the HTTP MIME type of the output stream Response.ContentType = "application/octet-stream"; // Write the data out to the client. Response.BinaryWrite(byteArray);