Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load excel file from resources/assembly in C#

I need to load an Excel file and write on it. I have already added the file to resources and set its build action to Embedded Resource. My problem is I can't seem to load it from the resources/assembly. I currently have this code:

 Assembly assembly = Assembly.GetExecutingAssembly();
        Assembly asm = Assembly.GetExecutingAssembly();
        string file = string.Format("{0}.UTReportTemplate.xls", asm.GetName().Name);
        var ms = new MemoryStream();
        Stream fileStream = asm.GetManifestResourceStream(file);

        xlWorkBook = xlApp.Workbooks.Open(file);
        if (xlApp == null)
        {
            MessageBox.Show("Error: Unable to create Excel file.");
            return;
        }
        xlApp.Visible = false;

What am I doing wrong? How can I access the file? Any help would be appreciated. Thanks.

like image 486
jaqui Avatar asked Apr 25 '13 02:04

jaqui


2 Answers

You need to extract the resource (in this case an excel spreadsheet) from the assembly and write it as a stream to a File, eg:

Assembly asm = Assembly.GetExecutingAssembly();
string file = string.Format("{0}.UTReportTemplate.xls", asm.GetName().Name);
Stream fileStream = asm.GetManifestResourceStream(file);
SaveStreamToFile(@"c:\Temp\Temp.xls",fileStream);  //<--here is where to save to disk
Excel.Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"c:\Temp\Temp.xls");
if (xlWorkBook  == null)
{
   MessageBox.Show("Error: Unable to open Excel file.");
   return;
}
//xlApp.Visible = false;

...

public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}
like image 129
Jeremy Thompson Avatar answered Oct 25 '22 18:10

Jeremy Thompson


//save resource to disk
string strPathToResource = @"c:\UTReportTemplate.xls";
using (FileStream cFileStream = new FileStream(strPathToResource, FileMode.Create))
 {
            cFileStream.Write(Resources.UTReportTemplate, 0, Resources.UTReportTemplate.Length);
 }

//open workbook
Excel.Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(strPathToResource);
if (xlWorkBook  == null)
{
   MessageBox.Show("Error: Unable to open Excel file.");
   return;
}
xlApp.Visible = false;
like image 36
Sergey1380528 Avatar answered Oct 25 '22 19:10

Sergey1380528