private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.SaveFileDialog saveFileDlg = new SaveFileDialog();
saveFileDlg.FileName = "报废信息";//默认文件名
saveFileDlg.DefaultExt = "xls";//默认后缀名
saveFileDlg.Filter = "Excel文件 (*.xls) |*.xls";
if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
doExport(saveFileDlg.FileName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "系统管理", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void doExport(string strExcelFileName)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
if (excel == null)
throw new Exception("无法启动Excel,可能您的计算机尚未安装Excel");
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);
if (dgvTrafficCalc != null && dgvTrafficCalc.Rows.Count > 0)
{
for (int i = 0; i < dgvTrafficCalc.ColumnCount; i++)
{
colIndex++;
excel.Cells[1, colIndex] = dgvTrafficCalc.Columns[i].Name;
}
foreach (DataGridViewRow row in dgvTrafficCalc.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataGridViewColumn col in dgvTrafficCalc.Columns)
{
colIndex++;
excel.Rows.Cells[rowIndex, colIndex] = row.Cells[col.Name].Value != null ? row.Cells[col.Name].Value.ToString() : "";
}
}
}
excel.Visible = false;
try
{
excel.ActiveWorkbook.SaveAs(strExcelFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
}
catch (Exception ex)
{
throw ex;
}
excel.Quit();
excel = null;
GC.Collect();//垃圾回收
}
//导入
string fileName = null;
this.openFileDialog1.Filter = "Excle文件(*.xls)|*.xls";
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = this.openFileDialog1.FileName;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileName + "';Extended Properties=Excel 8.0;";
DataSet myDataset = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
try
{
da.Fill(myDataset);
this.dgvTrafficCalc.DataSource = myDataset.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("读取文件错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Windows Forms 中 DataGridView 数据导入 导出 Excel
最新推荐文章于 2024-10-02 10:19:33 发布