从C#中的资源/程序集加载excel文件

jaq*_*qui 8 c# excel resources embedded-resource

我需要加载一个Excel文件并在上面写.我已经将文件添加到资源并将其构建操作设置为Embedded Resource.我的问题是我似乎无法从资源/程序集加载它.我目前有这个代码:

 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;
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我该如何访问该文件?任何帮助,将不胜感激.谢谢.

Jer*_*son 15

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;
Run Code Online (Sandbox Code Playgroud)

...

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);
     }
}
Run Code Online (Sandbox Code Playgroud)