【发布时间】:2016-08-20 10:20:32
【问题描述】:
这段代码在导出excel后总是跳过最后一行,你能检查一下代码有什么问题吗?
我变了
transcationTableDataGridView.Rows.Count - 1
到
transcationTableDataGridView.Rows.Count + 1
它确实将所有行导出到 excel 但抛出索引应该是非负错误此异常:
private void exportToExcel_Click(object sender, EventArgs e)
{
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Records";
try
{
for (int i = 1; i < transcationTableDataGridView.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = transcationTableDataGridView.Columns[i - 1].HeaderText;
}
for (int i = 0; i < transcationTableDataGridView.Rows.Count - 1; i++)
{
for (int j = 0; j < transcationTableDataGridView.Columns.Count; j++)
{
if (transcationTableDataGridView.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = transcationTableDataGridView.Rows[i].Cells[j].Value.ToString();
}
else
{
worksheet.Cells[i + 2, j + 1] = "";
}
}
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
app.Quit();
workbook = null;
worksheet = null;
}
}
catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
}
在某些计算机上导出时也会出错
我正在使用此代码:
using Excel=Microsoft.Office.Interop.Excel;
到此代码:
using System.Runtime.InteropServices;
谁能解释一下两者有什么区别?
【问题讨论】:
-
在二手电脑中使用 Microsoft.Office.Interop.Excel 库时,必须有 Microsoft Excel 程序。可能没有 Excel 程序当前 Comp
标签: c# excel datagridview