我试图将一些数据写入使用Microsoft Excel 2010创建的宏启用的Excel中。 问题是我的代码没有写任何数据,也没有错误。任何人都可以告诉我我的代码有什么问题吗?
private void button2_Click_1(object sender, EventArgs e)
{
string excelFilename;
excelFilename = "D:\\TestPivot1.xlsm";
Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();
Workbook ObjWorkBook;
Worksheet ObjWorkSheet;
ObjWorkBook = ObjExcel.Workbooks.Open(excelFilename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
ObjWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)ObjWorkBook.Sheets[2];
int i;
for(i=1;i<10;i++){
ObjWorkSheet.Cells[i, 1] = "ID";
ObjWorkSheet.Cells[i, 2] = "NAME";
ObjWorkSheet.Cells[i, 3] = "GENDER";
ObjWorkSheet.Cells[i, 4] = "DEPT";
ObjWorkSheet.Cells[i, 5] = "SALARY";
ObjWorkSheet.Cells[i, 6] = "DOH";
ObjWorkSheet.Cells[i, 7] = "LOCATION";
}
ObjWorkBook.SaveAs("D:\\TestPivot2.xlsm", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
}
答案 0 :(得分:0)
您将整个.xlsm文件传递给interop对象,然后首先创建文件流对象然后使用该对象打开excel,然后创建与您要修改的名称完全相同的工作簿对象。
错误:1)没有fileStream对象打开.xlsm文件 2)您正在传递filepath,您应该传递FileStream 3)当你完成所需的操作后,ObjWorkBook.Write(fs);然后关闭所有对象