我在编写C#代码,最终想要将生成的数组导出到Excel文件中。为此,我查找了示例代码以先运行模拟结果,然后再用于我的代码。我尝试使用Interop Excel实现代码,虽然代码能够运行,可以打开/创建工作簿、打开/创建工作表、重命名工作表、将结果保存下来,但是我无法更改单元格。无论值更改还是格式更改都不起作用。它会保存带有更改的空Excel文件。
请参见下面我尝试运行的示例代码:我正在使用Rider,但在Visual Studio中也失败了。还尝试从多台计算机上进行操作,但也不起作用。.NET框架是4.0.3,安装的Interop包是最新的15.0.4795(同时Microsoft Office Core也安装了最新的15.0.0版本)。CSV写入确实有效(请参见第一个代码片段中的注释部分)。
我不知道还能尝试什么,如果需要进一步的上下文信息,请告诉我。谢谢您的帮助!
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
public void ExcelExport()
{
var fileLoc = "...\\test.xlsx";
// CSV writer
// using (TextWriter sw = new StreamWriter(fileLoc))
// {
// string strData = "Zaara";
// float floatData = 324.563F;//Note it's a float not string
// sw.WriteLine("{0},{1}", strData, floatData.ToString("F2"));
// }
var excelApp = new Excel.Application();
excelApp.Visible = true;
excelApp.DisplayAlerts = false;
var workBook = (Excel.Workbook) excelApp.Workbooks.Add();
var reportSheet = (Excel.Worksheet) workBook.Worksheets.Add();
reportSheet.Name = "Report";
reportSheet.Cells[3, 4] = "Contract Name";
reportSheet.Range["A2, A2"].Value2 = 10;
workBook.SaveAs(fileLoc);
workBook.Close();
excelApp.DisplayAlerts = true;
excelApp.Quit();
}
public void ExcelExport2()
{
var fileLoc = "...\\test2.xlsx";
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
// Create an array to multiple values at once.
string[,] saNames = new string[5,2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
oWB.SaveAs(fileLoc, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close();
oXL.Quit();
}