public Form1()
{
InitializeComponent();
DataSet ds = new DataSet();
ds.ReadXml("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\Products.xml");
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
// Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
// Storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\test.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
{
InitializeComponent();
DataSet ds = new DataSet();
ds.ReadXml("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\Products.xml");
dataGridView1.DataSource = ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
// Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
// Storing Each row and column value to excel sheet
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\test.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
No comments:
Post a Comment