/// <summary>
/// 保存为Excel文件
/// </summary>
private void btnSaveExcel_Click(object sender, EventArgs e)
{
saveFileDialogSaveExcel.Filter = "Excel文件|*.XLS";
saveFileDialogSaveExcel.InitialDirectory = "C:\\";
if (saveFileDialogSaveExcel.ShowDialog() == DialogResult.Cancel)
{
return;
}
else
{
string fileName = saveFileDialogSaveExcel.FileName;
DataTable dt = (DataTable)this.dgvShow.DataSource;
if (dt != null)
{
//调用基本方法,生成Excel文件
SaveExcel(dt, fileName);
}
else
{
MessageBox.Show("当前表格中没有数据,不能保存!");
}
}
}
/// <summary>
/// 将DataTable保存为Execl的基本方法
/// </summary>
/// <param name="fileName">Excel文件路径</param>
public void SaveExcel(DataTable dt, string fileName)
{
int columnIndex=1;
int rowIndex=1;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlApp.DefaultFilePath = fileName;
xlApp.DisplayAlerts = true;
xlApp.SheetsInNewWorkbook = 1;
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
//将DataTable的列名导入Excel表第一行
foreach (DataColumn column in dt.Columns)
{
xlApp.Cells[rowIndex,columnIndex]=column.ColumnName;
columnIndex++;
}
//将DataTable中的数据导入Excel中
for (int i = 0; i < dt.Rows.Count; i++)
{
columnIndex = 1;
rowIndex++;
for (int j = 0; j < dt.Columns.Count; j++)
{
xlApp.Cells[rowIndex, columnIndex] = dt.Rows[i][j].ToString();
columnIndex++;
}
}
xlBook.SaveCopyAs(fileName);
xlApp = null;
xlBook = null;
System.Diagnostics.Process.Start(fileName);
MessageBox.Show("测试成功:Excel文件保存成功且正常打开!");
}