5

Hi I am using closedxML DLL for exporting to excel i have static method like this below

    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);           
    }

I am calling above function in a method like this below

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());            
 }

but i need to get that result excel sheet in bytes, I need to store it in memory stream later i can use for further purpose ..

But I am not sure how can i get the created excel file in bytes format...

Would any one pls give any idea or solutions on this one ... Many thanks In advance ...

4

3 回答 3

15

关闭的 XML 工作簿被保存到流中。您可以使用内存流。然后调用MemoryStream.ToArray()以获取其字节。所以...

var wb = new XLWorkbook();
//...
var workbookBytes = new byte[0];
using (var ms = new MemoryStream())
{
    wb.SaveAs(ms);
    workbookBytes = ms.ToArray();
}
于 2018-08-23T13:15:20.817 回答
2

请这样做:-

//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);
于 2013-09-30T10:10:33.683 回答
1

我知道这个问题很老,但对于那些在这里磕磕绊绊的人来说。

在工作簿上,您可以使用 SaveAs 方法将其保存到流中,然后使用 MemoryStream 返回字节

public byte[] GetExcelAsBytes()
{
    try
    {
        using (MemoryStream fs = new MemoryStream())
        {
            mWorkBook.SaveAs(fs);
            fs.Position = 0;
            return fs.ToArray();
        }
    }
    catch(Exception ex)
    {
        return new byte[] { };
    }
}
于 2020-09-30T09:17:14.790 回答