简体   繁体   中英

Using ExcelPackage to Read from Excel Template and Write to Excel

I am using the following bit of code:

var assembly =          Assembly.GetExecutingAssembly();
        Stream streamToTemplete=assembly.GetManifestResourceStream("DailyAuction.xltx");
        Stream streamToOutput = assembly.GetManifestResourceStream("dailyAuctionEmail.xls");


        //using (ExcelPackage excelPackage = new ExcelPackage(newFile, templateFile))

        using(streamToTemplete)
        using (streamToOutput)
        {

            using (ExcelPackage excelPackage = new ExcelPackage(streamToOutput, streamToTemplete))
            {

                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["Daily Auction"];
                int startRow = 4;
                int row = startRow;
                foreach (DailyEmail dailyEmail in listDailyEmail)                                                                                                                           //iterate through all the rows in the list
                {
                    worksheet.Cells[row, 1].Value = dailyEmail.As_At.ToString("dd-MMM-yy HH:mm");
                    worksheet.Cells[row, 2].Value = dailyEmail.Auction_Date.ToString("dd-MMM-yy");

                }
                excelPackage.Save();
            }
        }

        var attachment = new Attachment(streamToOutput, new ContentType("application/vnd.ms-excel"));

However, I am getting an error saying streamToTemplate & streamToOutput are null. What seems to be the problem? Also, will the rest of the code work?

Check the properties on both the Excel files. Build Action should be 'Embedded Resource'.

Also, the string that you are providing to GetManifestResource stream looks too simple. The string should be:

<defaultNamespace>.<folderName>.<fileName> MSDN Article

This answer suggests calling the GetManifestResourceNames, then using the debugger to take a look at the resource names. Seems a good way to go while you're finding your way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM