当我以 .NET 3.5 为目标时,我有以下代码可以正常工作:
Microsoft.Office.Interop.Excel.Application _excelInstance;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook;
_excelInstance = new Microsoft.Office.Interop.Excel.Application();
_excelWorkbook = _excelInstance.Workbooks.Add();
_excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)_excelWorkbook.Worksheets.get_Item(1);
但是,当我以 .NET 4.5 为目标时,编译器对上面的最后一行给出以下错误:
找不到编译动态表达式所需的一种或多种类型。您是否缺少参考?
我无法为这个项目定位 .NET 3.5,它必须是 4.0 或 4.5。
知道是什么原因造成的,或者我应该如何解决这个问题?
谢谢。
编辑 -
这是整个类:
public class ExcelWriter : IDisposable
{
private string _outputFile;
public ExcelWriter(string outputFile)
{
_outputFile = outputFile;
}
public void Write(List<string[]> data)
{
Microsoft.Office.Interop.Excel.Application _excelInstance;
Microsoft.Office.Interop.Excel.Worksheet _excelWorksheet;
Microsoft.Office.Interop.Excel.Workbook _excelWorkbook;
_excelInstance = new Microsoft.Office.Interop.Excel.Application();
_excelWorkbook = _excelInstance.Workbooks.Add();
_excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)_excelWorkbook.Worksheets.get_Item(1);
int rowNumber = 1;
foreach (var row in data)
{
int columnNumber = 1;
foreach (var field in row)
{
_excelWorksheet.Cells[rowNumber, columnNumber] = field;
columnNumber++;
}
rowNumber++;
}
if (File.Exists(_outputFile))
{
File.Delete(_outputFile);
}
_excelWorkbook.SaveAs(_outputFile);
_excelWorkbook.Close();
_excelInstance.Quit();
}
public void Dispose()
{
if (File.Exists(_outputFile))
{
File.Delete(_outputFile);
}
}
}