C#将DataGridView中数据导出为Excel
C#将DataGridView中数据导出为Excel
转自https://blog.csdn.net/weixin_43826109/article/details/105182489
1、首先需要添加Microsoft Office 16.0 Object Library
2、导入引用using Excel = Microsoft.Office.Interop.Excel;
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = "Excel文件|*.xlsx|Excel(2003文件)|*.xls";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string path = fileDialog.FileName;
Excel.Application application = new Excel.Application();
Excel.Workbooks workbooks = application.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = workbook.Worksheets[1];
int colIndex = 0;
//导出DataGridView中的标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (dataGridView1.Columns[i].Visible)//做同于不导出隐藏列
{
colIndex++;
worksheet.Cells[1, colIndex] = dataGridView1.Columns[i].HeaderText;
}
}
//导出DataGridView中的数据
for (int i = 0; i < dataGridView1.RowCount; i++)
{
colIndex = 0;
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (dataGridView1.Columns[j].Visible)
{
colIndex++;
worksheet.Cells[i + 2, colIndex] = "'"+dataGridView1.Rows[i].Cells[j].Value;
}
}
}
//保存文件
workbook.SaveAs(fileDialog.FileName);
application.Quit();
MessageBox.Show("导出成功");
}
private void btnExport_Click(object sender, EventArgs e) //点击导出到Excel表按钮
{
string fileName = "";
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
//写入标题
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{ worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
//写入数值
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName); //fileSaved = true;
}
catch (Exception ex)
{//fileSaved = false;
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
}