先添加引用程序集 Microsoft.Office.Interop.Excel
聲明 using Excel = Microsoft.Office.Interop.Excel;
以及貼出方法:
//DataGridView數據導出Excel
private void ExportExcel(string fileName, DataGridView myDGV)
{
string saveFileName = "";
//bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0)
return; //被點了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("無法創建Excel對象,可能您的機子未安裝Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
string[] array = new string[myDGV.Columns.Count];
//獲取Visble =true 的列
foreach (DataGridViewColumn column in myDGV.Columns)
{
if (column.Visible == true)
{
array[column.DisplayIndex] = column.HeaderText + '|' + column.Name; ;
}
}
int RowsCount = myDGV.Rows.Count;
int ColumnsCount = array.Length;
int mm = 1;
for (int i = 0; i < ColumnsCount; i++)
{
string[] str =new string[2];
string ColumnName;
try
{
str = array.GetValue(i).ToString().Split('|');
ColumnName = str[0];
}
catch
{
continue;
}
//導出列名 www.2cto.com
worksheet.Cells[1, mm] = ColumnName;
//導出列內容
for (int m = 0; m < RowsCount; m++)
{
try
{
worksheet.Cells[m + 2, mm] = myDGV.Rows[m].Cells[str[1]].FormattedValue.ToString();
}
catch
{ }
}
//執行完一列 mm++
mm++;
}
worksheet.Columns.EntireColumn.AutoFit();
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex)
{
MessageBox.Show("導出文件時出錯,文件可能正被打開!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//強行銷毀
MessageBox.Show(fileName + "的表格資料保存成功", "提示", MessageBoxButtons.OK);
}
摘自 邱征響的專欄