首页 > 代码库 > c# winform导出Excel
c# winform导出Excel
//需要注意添加引用Microsoft.Office.Interop.Excel.dll
string fileName =DateTime.Now.Year+ DateTime.Now.Month+ DateTime.Now.Day + ".xls"; if (showView.Rows.Count > 0) { string saveFileName = ""; //bool fileSaved = false; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xls"; saveDialog.Filter = "Excel文件|*.xls"; 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 < showView.ColumnCount; i++) { worksheet.Cells[1, i + 1] = showView.Columns[i].HeaderText; } //写入数值 for (int r = 0; r < showView.Rows.Count; r++) { for (int i = 0; i < showView.ColumnCount; i++) { worksheet.Cells[r + 2, i + 1] = showView.Rows[r].Cells[i].Value; } System.Windows.Forms.Application.DoEvents(); } worksheet.Columns.EntireColumn.AutoFit();//列宽自适应 if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); //fileSaved = true; } catch (Exception ex) { MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message); } } xlApp.Quit(); GC.Collect();//强行销毁 MessageBox.Show(fileName + "的资料保存成功", "提示", MessageBoxButtons.OK); } else { MessageBox.Show("报表为空,无表格需要导出", "提示", MessageBoxButtons.OK); }
c# winform导出Excel
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。