namespace dxhbskymDemo { public partial class ExcelForm : DevExpress.XtraEditors.XtraForm { public ExcelForm() { InitializeComponent(); } #region 导出Excel //导出按钮 private void sbtnDaochu_Click(object sender, EventArgs e) { string fileName = "";//要保存的excel文件名 SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "导出Excel(*.xls)|*.xls";//扩展名 sfd.FileName = "河北省项目汇总表";// if (sfd.ShowDialog() == DialogResult.OK) { fileName = sfd.FileName; //导入 outPutExcel(fileName); } }
//导出Excel的方法 private void outPutExcel(string saveFilepath) { bool isShowExcel = false; DataTable dt = new DataTable();//将数据库取出的数据源转成DataTable if (dt == null) { return; } if (dt.Rows.Count == 0) { return; } Missing miss = Missing.Value; Excel.Application xlApp = new Excel.Application(); if (xlApp == null) { XtraMessageBox.Show("请确保您的电脑已经安装Excel!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //xlApp.UserControl = true; Excel.Workbooks workBooks = xlApp.Workbooks; //Excel.Workbook workBook = workBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);//创建新的 Excel.Workbook workBook = workBooks.Add(System.AppDomain.CurrentDomain.BaseDirectory + "excel\\项目汇总表.xls");//根据现有excel模板产生新的Workbook Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];//获取sheet1 if (workSheet == null) { XtraMessageBox.Show("请确保您的电脑已经安装Excel!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { Excel.Range range=null; xlApp.Visible = isShowExcel;//若是true,则在导出的时候会显示excel界面 int totalCount = dt.Rows.Count; workSheet.Cells[1, 1] = "河北省石家庄市项目汇总表";//导出标题 //写入数值 for (int i = 0; i < dt.Rows.Count; i++) { workSheet.Cells[i + 4, 1] = dt.Rows[i]["xmxh"];//项目序号 //workSheet.Cells[5,1]=””;//表示第五行与第一列交点的那个单元格坐标
workSheet.Cells[i + 4, 2] = dt.Rows[i]["xmmc"];//项目名称 ((Excel.Range)workSheet.Cells[i+4, 2]).ColumnWidth = 12;//设置列宽
workSheet.Cells[i + 4, 3] = dt.Rows[i]["bz"];//备注 } workSheet.SaveAs(saveFilepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); workBooks.Close(); } catch (Exception ex) { XtraMessageBox.Show("Excel导出失败,错误:" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information); xlApp.Quit(); regExpre.KillExcelProcess(); } finally { xlApp.Quit(); regExpre.KillExcelProcess(); } } #endregion } }