c#使用嵌入式资源中的excel文件

我正在为我的女朋友写一个评分程序,我试图将数据输出到我嵌入到程序中的excel文件中。 我目前正在写一个空白的excel文件,但是想使用预先制作的excel文件并将数据导出到适当的单元格。 我无法弄清楚如何告诉程序在资源文件夹中使用xls文件而不是制作一个空白的excel文件。 这是迄今为止保存它的代码。 我正在使用C#2008快递版。

谢谢

我的资源参考是:Properties.Resources.gradesheet

Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add data to excel xlWorkSheet.Cells[1, 1] = firstName; xlWorkSheet.Cells[2, 1] = lastName; xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); 

您需要从资源中获取excel文件并将其保存到文件中。 然后你可以在工作簿上打开一个:

 xlApp.Workbooks.Open(fileName); 

这应该可以帮到你。 (在.NET 4.5中测试)。

 public void openExcelTemplateFromResources () { string tempPath = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource); Excel.Application excelApplication = new Excel.Application(); Excel._Workbook excelWorkbook; excelWorkbook = excelApplication.Workbooks.Open(tempPath) excelApplication.Visible = true; // at this point its up to the user to save the file } 

正如John Koerner所说,Excel可以处理文件,因此您需要先将Excel文件保存到文件中。

但是,如果您可以使用.XLSX而不是.XLS,那么您最好使用EPPlus而不是Interop来创建Excel文件。 它更容易,并没有Interop所做的所有问题。

根据此链接,取决于您要对Excel文件执行的操作,以及您将如何使用它,该方案略有不同。 您可以:

  • 将流直接传递给支持流作为参数的对象。 例如, Excel Package Plus支持直接从任何流中读取excel文件,并可以将对象加载到内存中。 然后,您可以操作该对象并将其写入调用Save方法的文件,传递filename filestreamfilename
  • 通过创建具有正确目标文件名的可写Filestream对象(使用File.OpenWrite)然后调用yourManifestResourceStream.CopyTo(yourFileStream),将流保存到(临时)文件。 然后,您可以将filename传递给另一个进程(例如Excel)并从文件系统中打开它。

首先,您应该使用此函数获取资源文件的流:

  public static Stream GetResourceFileStream(string fileName) { Assembly currentAssembly = Assembly.GetExecutingAssembly(); // Get all embedded resources string[] arrResources = currentAssembly.GetManifestResourceNames(); foreach (string resourceName in arrResources) { if (resourceName.Contains(fileName)) { return currentAssembly.GetManifestResourceStream(resourceName); } } return null; } 

然后您可以使用流或您可以将流保存到文件: 如何将流保存到文件 。

您可以创建Excel模板文件( .xlt ),然后根据该模板打开新的.xls文件。 此致,AB