【#文档大全网# 导语】以下是®文档大全网的小编为您整理的《学习笔记2》,欢迎阅读!
学习笔记2
学会 使用PNOI 把datatable 转换成 Execl 电子表 代码:
protected void Bug_Click(object sender, EventArgs e) {
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name"); dt.Columns.Add("Date");
for (int i = 1; i <= 10; i++) {
dt.Rows.Add(new object[] { i, "xfs" + i, new DateTime(2013, 11, i) }; } try {
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); Response.BinaryWrite(DataTable2Excel(dt, "text_")); }
catch (Exception ex) {
} finally {
}
}
//定义只读 变量 控制 每页 Excel 最大行 Readonly int EXCEL03_MaxRow = 65535; /// /// 得到一个内存流 ///
/// /// ///
Public byte[] DataTable2Excel(DataTable dt, string sheetName)
{
//创建一个Excel _ book
IWorkbook book = new HSSFWorkbook(); if (dt.Rows.Count < EXCEL03_MaxRow)
DataWrite2Sheet(dt, 0, dt.Rows.Count - 1, book, sheetName); else {
int page = dt.Rows.Count / EXCEL03_MaxRow; for (int i = 0; i < page; i++) {
int start = i * EXCEL03_MaxRow;//得到起始行的下标
int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - 1;//得到终下标 DataWrite2Sheet(dt, start, end, book, sheetName + i.ToString()); }
//获取最后的一页
int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow;
DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, dt.Rows.Count, book, sheetName + page.ToString()); }
MemoryStream ms = new MemoryStream(); book.Write(ms); return ms.ToArray(); }
private void DataWrite2Sheet(DataTable dt, int startRow, int endRow, IWorkbook book, string sheetName) {
//给book 创建Sheet
ISheet sheet = book.CreateSheet(sheetName); //在创建的sheet里面创建第一行 IRow header = sheet.CreateRow(0); //给dt 设置标题
for (int i = 0; i < dt.Columns.Count; i++) {
//在第一行里面创建第i列 ICell cell = header.CreateCell(i); //获取第i列的标题放到val
string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName; //在给第一行第i列写入值val cell.SetCellValue(val); }
int rowIndex = 1;
//这里循环次数为每页的 的行数 for (int i = startRow; i <= endRow; i++) {
//创建数据行 这一行是dt的第i行 DataRow dtRow = dt.Rows[i];
//创建Excel的行这一行是sheet创建的第rowIndex++行 IRow excelRow = sheet.CreateRow(rowIndex++); for (int j = 0; j < dtRow.ItemArray.Length; j++) {
//在rowIndex++行的给第j列 写入 dt的第i行第j列的值 ICell cell = excelRow.CreateCell(j); cell.SetCellValue(dtRow[j].ToString());
if (j == 2) {
ICellStyle cellStyle = book.CreateCellStyle(); IDataFormat format = book.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("yyyy年m月d日"); cell.CellStyle = cellStyle; } } }
}
明天继续努力!!!!
本文来源:https://www.wddqxz.cn/b5c152930029bd64783e2c41.html