標籤:
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模板匯出資料