导出Excel 文件

引用类库:using Aspose.Cells;

 /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            DataTable dtr = ds.Tables[0];
            Export(dtr, "拣货信息表.xlsx", false);
        }
        /// <summary> 
        /// 导出Excel
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="fileName"></param>
        /// <param name="tipOpenfile"></param>
        public void Export(DataTable dataTable, string fileName, bool tipOpenfile = false)
        {
            if (fileName == null || dataTable == null) return;
            if (File.Exists(fileName) && (MessageBox.Show("文件已存在,是否覆盖?", "提示", MessageBoxButtons.YesNo)
                    == System.Windows.Forms.DialogResult.No)) return;
            try
            {
                Workbook wb = new Workbook();
                Worksheet ws = wb.Worksheets[0];
                ws.Name = dataTable.TableName == null ? "Sheet1" : dataTable.TableName;
                Cells cell = ws.Cells;
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    cell[0, i].PutValue(dataTable.Columns[i].ColumnName);
                    for (int j = 0; j <dataTable.Rows.Count; j++)
                    {
                      
                        cell[j + 1, i].PutValue(dataTable.Rows[j][i]);
                    }
                }
                ws.AutoFitColumns();
                wb.Save(fileName);
                if (tipOpenfile && (MessageBox.Show("导出成功,立即打开文件?", "提示", MessageBoxButtons.YesNo)
                    == System.Windows.Forms.DialogResult.Yes)) Process.Start(fileName);
            }
            catch (Exception er)
            {
                MessageBox.Show("导出失败\r\n" + er.Message);
            }
        }

  

posted @ 2019-09-05 17:25  下边的风  阅读(148)  评论(0编辑  收藏  举报