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.
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);
}
}
//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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With