将excel文件合并到项目目录wpf c#

我有一些信息存储在Excel文件中,我想从Wpf应用程序读取它们。 我可以用这种方式读取这个文件:

foreach (var worksheet in Workbook.Worksheets("ExcelFile.xlsx") ) { for (int j = 1; j < 30; j++) { _Data.Add(new Data { FirstElement = worksheet.Rows[j].Cells[0].Text.ToString(), }); } } 

ExcelFile.xlsx是解决scheme文件夹中保存的文件,并设置为“合并资源”。 如果我直接从Visual Studio启动应用程序,它的工作原理,但如果我复制编译的.exe文件,并将其发送给某人,它不起作用,因为xlsx文件丢失。

我的问题是:有没有办法将xlsx文件合并到.exe文件中,这样我就可以共享.exe文件,一切正常。 为什么将ExcelFile.xlsx文件设置为“ 合并资源 ”不能按我的想法工作?

谢谢你的帮助!

我通过将文件添加到项目并将其Build Action属性更改为Embedded Resource来实现。

然后,您可以将文件显示为用户硬盘上的临时文件,如下所示:

 // Create the template as a temporary file string pathTemplate = Path.GetTempFileName(); Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream input = assembly.GetManifestResourceStream("Vol_Report.Vol Report Template.xlsm")) // Note that it is Vol_Report because my namespace was Vol Report using (Stream output = File.Create(pathTemplate)) { input.CopyTo(output); } 

然后像这样读取文件

 app = new Excel.Application(); app.DisplayAlerts = false; Excel.Workbooks books = app.Workbooks; book = books.Open(pathTemplate); 

注意上面的代码片段假定using Excel = Microsoft.Office.Interop.Excel;

然后在最后你可以像这样删除临时文件

 File.Delete(pathTemplate); 

但是,我需要操纵文件并写入文件。 既然你只是从文件中读取,可能会有一个更简单的方法。 尝试通过右键单击项目,select属性并单击添加资源 – >在资源选项卡下添加现有文件,将文件添加为项目资源。 那么你应该能够得到你的文件

 Workbook.Worksheets(Properties.Resources.ExcelFile)