使用前添加using Excel =Microsoft.Office.Interop.Excel;
并添加引用DLL文件:
方法一:
dataGridView1替换为对应的控件Name;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出EXCEL格式数据";
saveFileDialog.ShowDialog();
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Excel.Application excel = new Excel.ApplicationClass();
Excel.Workbooks books = (Excel.Workbooks)excel.Workbooks;
Excel.Workbook book = (Excel.Workbook)(books.Add(miss));
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
sheet.Name = "sheet1";
int colIndex = 0;
foreach (DataGridViewColumn column in dataGridView2.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = column.HeaderText;
}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
excel.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value;
}
}
String strName = saveFileDialog.FileName.ToString();
if (strName != "")
{
try
{
sheet.SaveAs(strName, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
}
catch (Exception ex)
{
String errorinfo = ex.Message.ToString() + "请先关闭这个文件。";
MessageBox.Show(errorinfo);
}
book.Close(false, miss, miss);
books.Close();
excel.Quit();
MessageBox.Show("成功导出数据!");
}
//System.Runtime.InteropServices.Marshal.ReleaseComObject();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
GC.Collect();
============================分割线=================================
方法二:
dataGridView2替换为相应控件的Name;
//建立Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Visible = true;
//生成字段名称
for (int i = 0; i < dataGridView2.ColumnCount; i++)
{
excel.Cells[1, i + 1] = dataGridView2.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < dataGridView2.RowCount - 1; i++)
{
for (int j = 0; j < dataGridView2.ColumnCount; j++)
{
if (dataGridView2[j, i].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "'" + dataGridView2[j, i].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = dataGridView2[j, i].Value.ToString();
}
}
}
//保存方式二结束