سلام
من قبلا از این روش استفاده میکرم بعد که پروژه بزرگتر شد وجود کلاس اکسل در دیتاتیبل تداخل ایجاد کرد نمیدونم خیلی تلاش کردم نشد میبایست کل اسم کلاس رو توی هر سطر مینوشتی
//try
//{
// // creating Excel Application
// _Application app = new Microsoft.Office.Interop.Excel.Application();
// // creating new WorkBook within Excel application
// _Workbook workbook = app.Workbooks.Add(Type.Missing);
// // creating new Excelsheet in workbook
// _Worksheet worksheet = null;
// // see the excel sheet behind the program
// app.Visible = true;
// // get the reference of first sheet. By default its name is Sheet1.
// // store its reference to worksheet
// worksheet = (Worksheet)workbook.Sheets["Sheet1"];
// worksheet = (Worksheet)workbook.ActiveSheet;
// // changing the name of active sheet
// worksheet.Name = "Exported from gridview";
// // storing header part in Excel
// for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
// {
// worksheet.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++)
// {
// worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
// }
// }
// // save the application
// // workbook.SaveAs("g:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// SaveFileDialog sfd = new SaveFileDialog();
// sfd.Filter = "Excel Document(*.xlsx)|*.xlsx";
// // sfd.FileName = "Export";
// if (sfd.ShowDialog() == DialogResult.OK)
// {
// workbook.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// }
// // Exit from the application
// wait();
// app.Quit();
//}
//catch (Exception)
//{
// throw;
//}
//finally
//{
// endwait();
//}
بعد بفکر افتادم روش راحت و بی دردسر بدون کلاس و dll ببین
بسیار راحت فقط لازمه گزینه allowuseraddRow رو منفی کنی
string xls = string.Empty;
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
xls += column.HeaderText + ',';
}
xls += "\r\n";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
xls += cell.Value.ToString().Replace(",", ";") + ',';
}
xls += "\r\n";
}
string folderPath = "g:\\";
File.WriteAllText(folderPath + "myexel.CSV", xls);
MessageBox.Show("Export To Exel Success");
}