This code always skips last row after exporting excel, can you check what's wrong in the code?
I changed
transcationTableDataGridView.Rows.Count - 1
to
transcationTableDataGridView.Rows.Count + 1
it does export all rows to excel but throws index should be non-negative error this exception:
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()); }
}
It also gives me error during export in some computers
I was using this code:
using Excel=Microsoft.Office.Interop.Excel;
to this code:
using System.Runtime.InteropServices;
can anyone explain what is the difference between two?
i have one repiring to out full data to excl you can use this code private void button22_Click(object sender, EventArgs e) {