Execl完美导出
今天需要做个excel导入导出的,小弟先搞个导出的,感觉还蛮不错很方便详细看下文:
1、引入org.in2bits.MyXls.dll 这个dll引入后什么问题都简单了
前台code
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="导出EXCEL" />
后台code
protected void Button1_Click(object sender, EventArgs e) { NewsService service = new NewsService(); DataTable dt = service.Get_AllData_Table(); TableTOExcel(dt, "double.xls"); } #region "导出EXCEL" /// <summary> /// 绑定数据库生成XLS报表 /// </summary> /// <param name="ds">获取DataSet数据集</param> /// <param name="xlsName">报表表名</param> public static void TableTOExcel(DataTable table, string xlsName) { if (table == null) return; XlsDocument xls = new XlsDocument(); xls.FileName = xlsName; int rowIndex = 1; DataTable dt2 = null; int maxlen = 65500; int rowcount = table.Rows.Count; for (int p = 0; p <= rowcount / maxlen; p++) { dt2 = SplitDataTbale(table, maxlen, p); rowIndex = 1; Worksheet sheet = xls.Workbook.Worksheets.AddNamed("sheet" + (p + 1).ToString());//状态栏标题名称 Cells cells = sheet.Cells; for (int i = 0; i < table.Columns.Count; i++) { cells.AddValueCell(1, i + 1, dt2.Columns[i].ColumnName); } foreach (DataRow row in dt2.Rows) { rowIndex++; for (int j = 0; j < dt2.Columns.Count; j++) { sheet.Cells.AddValueCell(rowIndex, j + 1, row[j].ToString()); } } } xls.Send(); } private static DataTable SplitDataTbale(DataTable dt, int RowCount, int p) { DataTable dt2 = new DataTable("temp"); for (int j = 0; j < dt.Columns.Count; j++) { dt2.Columns.Add(new DataColumn(dt.Columns[j].ColumnName, dt.Columns[j].DataType)); } for (int i = p * RowCount; i < p * RowCount + RowCount && i < dt.Rows.Count; i++) { DataRow dr = dt2.NewRow(); for (int k = 0; k < dt.Columns.Count; k++) dr[k] = dt.Rows[i][k]; dt2.Rows.Add(dr); } return dt2; } #endregion
其中 DataTable dt = service.Get_AllData_Table();就是获取一个这个表的所有data table,不用我这种方法也行~
点击导出就完美导出了~~~在下新手请各位大牛指教~