1、在项目的引入中,引入Microsoft.Office.Interop.Excel程序集,最好的11.0版本的。
2、在源文件中的using 中,使用using Excel = Microsoft.Office.Interop.Excel;
3、类似函数:
/// <summary>
/// 导出Excel的方法
/// </summary>
private void ExportExcel(DataGridView ds)
{
//DataSet ds = ;//数据源
if (ds == null) return;
string saveFileName = "";
bool fileSaved = false;
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel|*.xls";
saveDialog.FileName = "london";
if (saveDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
saveFileName = saveDialog.FileName;
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
MessageBox.Show("未安装Excel");
return;
}
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets[1];//取得sheet1
int index = 0;
List<string> listExcelColumns = new List<string>();
//写入字段
for (int i = 0; i < ds.Columns.Count; i++)
{
if (ds.Columns[i].Visible)
{
worksheet.Cells[1, index + 1] = ds.Columns[i].HeaderText;
listExcelColumns.Add(ds.Columns[i].Name);
index++;
}
}
//写入数值
for (int r = 0; r < ds.Rows.Count; r++)
{
index = 0;
for (int i = 0; i < ds.Columns.Count; i++)
{
if (ds.Columns[i].Visible)
{
worksheet.Cells[r + 2, index + 1] = ds.Rows[r].Cells[i].Value;
index++;
}
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
int column = 0;
column = listExcelColumns.IndexOf("UpdateTime") + 1;
Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, column], worksheet.Cells[ds.Rows.Count + 1, column]);//worksheet.Range[worksheet.Cells[2, column], worksheet.Cells[ds.Rows.Count + 1, column]];
rg.NumberFormat = "yyyy-MM-dd HH:mm:ss"; // 日期时间列的自定义显示格式,默认的不显示秒
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
workbook.SaveAs(saveFileName,
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
MessageBox.Show("保存失败");
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
}
}