使用NPOI,点击右键菜单生成报表,写入excel,出现异常。调试点了没反应,程序也没崩,也没停在哪个地方。
private void toolStripMenuItem5_Click(object sender, EventArgs e)
{
if (((TextBox) Controls.Find("textbox1", true)[0]).Text != null &&
((TextBox) Controls.Find("textbox2", true)[0]).Text != null &&
((TextBox) Controls.Find("textbox3", true)[0]).Text != null &&
((TextBox) Controls.Find("textbox4", true)[0]).Text != null &&
((TextBox) Controls.Find("textbox5", true)[0]).Text != null &&
((TextBox) Controls.Find("textbox6", true)[0]).Text != null )
{
string WriteExcelPath = @"../../工艺报表.xlsx";
using (FileStream fs = new FileStream(WriteExcelPath, FileMode.Open, FileAccess.ReadWrite))
{
IWorkbook workbook = new XSSFWorkbook(fs);
ISheet sheet = workbook.GetSheet("sheet1");
IRow row = sheet.GetRow(1);
row.GetCell(0).SetCellValue(((TextBox) Controls.Find("textbox1", true)[0]).Text);
//MessageBox.Show(((TextBox) Controls.Find("textbox1", true)[0]).Text);
row.GetCell(1).SetCellValue(((TextBox) Controls.Find("textbox2", true)[0]).Text);
row.GetCell(2).SetCellValue(((TextBox) Controls.Find("textbox3", true)[0]).Text);
row.GetCell(3).SetCellValue(((TextBox) Controls.Find("textbox4", true)[0]).Text);
row.GetCell(4).SetCellValue(((TextBox) Controls.Find("textbox5", true)[0]).Text);
row.GetCell(5).SetCellValue(((TextBox) Controls.Find("textbox6", true)[0]).Text);
//Exception of type System.InvalidOperationException was thrown
workbook.Write(fs);
//fs.Close();
}
}
}
代码是按照官方示例写的啊
错误提示:
用MemoryStream接收,最终生成完了再写到文件里。
这是没加载到文件吧 你把FileMode的Open改成OpenOrCreate或者Create试试