从C#中的资源/汇编加载excel文件 [英] Load excel file from resources/assembly in C#

查看:223
本文介绍了从C#中的资源/汇编加载excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要加载一个Excel文件并写上它。我已经将文件添加到资源中,并将其构建操作设置为嵌入式资源。我的问题是我似乎无法从资源/程序集加载它。我现在有这个代码:

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.

推荐答案

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

这篇关于从C#中的资源/汇编加载excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆