源代码:
private void ExportExcel(string fileName, DevExpress.XtraGrid.Views.Grid.GridView myDGV)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xlsx";
saveDialog.Filter = "Excel文件|*.xlsx";
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
int j = 0;//筛选掉隐藏的列
//写入标题
for (int i = 0; i < myDGV.Columns.Count; i++)
{
//myDGV.Columns[i].HeaderText;
if (myDGV.Columns[i].Visible == true)
{
worksheet.Cells[1, j + 1] = myDGV.Columns[i].Caption;
j++;
}
}
//写入数值
for (int r = 0; r < myDGV.RowCount; r++)
{
int k = 0;//筛选掉隐藏的列
for (int i = 0; i < myDGV.Columns.Count; i++)
{
if (myDGV.Columns[i].Visible == true)
{
worksheet.Cells[r + 2, k + 1] = myDGV.GetRowCellValue(r, myDGV.Columns[i]);
k++;
}
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开! " + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
MyCommon.ShowMessageBox(this, fileName + ".xlsx 导出成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//导出按钮事件
private void button3_Click(object sender, EventArgs e)
{
//第一个是名称,第二个是gridview
ExportExcel("测试", gridView1);
}
需要注意的是:在导出中gridview中的列要按顺序排列出来,要和前台显示保持一致,这里增加了隐藏列的方法,可以将隐藏的列筛选出来,office中2010以下的版本需要修改
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
以上的版本就不用修改了,动态创建出来了;