我正在使用互操作库从数据表创建 excel,所以我的方法很简单:public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType){ Microsoft.Office.Interop.Excel.Application excel; Microsoft.Office.Interop.Excel.Workbook excelworkBook; Microsoft.Office.Interop.Excel.Worksheet excelSheet; Microsoft.Office.Interop.Excel.Range excelCellrange; try { // Start Excel and get Application object. excel = new Microsoft.Office.Interop.Excel.Application(); // for making Excel visible excel.Visible = false; excel.DisplayAlerts = false; // Creation a new Workbook excelworkBook = excel.Workbooks.Add(Type.Missing); // Workk sheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet; excelSheet.Name = worksheetName; excelSheet.Cells[1, 1] = ReporType; excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString(); // loop through each row and add values to our sheet int rowcount = 2; foreach (DataRow datarow in dataTable.Rows) { rowcount += 1; for (int i = 1; i <= dataTable.Columns.Count; i++) { // on the first iteration we add the column headers if (rowcount == 3) { excelSheet.Cells[2, i] = dataTable.Columns[i - 1].ColumnName; excelSheet.Cells.Font.Color = System.Drawing.Color.Black; }如您所见,我正在使用以下代码将 excel 保存到路径:excelworkBook.SaveAs(saveAsLocation);调用此方法后,我用它 Process.Start(fileName);来打开 excel 文件。它工作得很好,但我想要实现的是打开这个 excel 而不将它保存到我只想打开的路径,比如临时文件。我怎样才能做到这一点?
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
您正在保存文件而不是显示您的 Excel 实例:
...
//now save the workbook and exit Excel
//excelworkBook.SaveAs(saveAsLocation); ;
//excelworkBook.Close();
//excel.Quit();
excel.Visible = true;
return true;
}
您首先设置excel.Visible = false;,这将使 excel 作为后台进程。相反,在范围的末尾,excel.Visible = true;在所有计算完成后添加。我注释掉了不需要的行,以便您可以看到我将新行放在哪里。
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
0/150
提交
取消