首页 > 代码库 > C# Winform Excel的导出,根据excel模板导出数据
C# Winform Excel的导出,根据excel模板导出数据
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 }}
C# Winform Excel的导出,根据excel模板导出数据
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。