I have the following code:
private void btnExcel_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
Microsoft.Office.Interop.Excel.Application XcelApp = new Microsoft.Office.Interop.Excel.Application();
XcelApp.Application.Workbooks.Add(Type.Missing);
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
XcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
try // catches null cells and ignores
{
for (int j = 0; j < dataGridView1.Columns.Count; j += 2)
{
XcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
catch (NullReferenceException)
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.InnerException);
}
}
XcelApp.Columns.AutoFit();
XcelApp.Visible = true;
string pathway = @"C:\Temp\" + txtComputer.Text + "." + lblVersion.Text + "." + lblProduct.Text + ".csv";
XcelApp.GetSaveAsFilename(pathway, "CSV (Comma Delimited) (*.csv), *.csv",2, DialogResult.OK);
}
}
This outputs a datagridview to an excel spreadsheet, opens it and then opens the save file dialogue box to save the document as CSV. I have several issues:
Thanks
private void btnExcel_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
Microsoft.Office.Interop.Excel.Application XcelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkBook = XcelApp.Workbooks.Add();
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
XcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
try // catches null cells and ignores
{
for (int j = 0; j < dataGridView1.Columns.Count; j += 2)
{
XcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
catch (NullReferenceException)
{
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n" + ex.InnerException);
}
}
string pathway = @"C:\Temp\" + txtComputer.Text + "." + lblVersion.Text + "." + lblProduct.Text + ".csv";
excelWorkBook.SaveAs(pathway, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
XcelApp.Workbooks.Close();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.