ExcelHandle
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web; namespace MVCStudy.Helper
{
public class ExcelHandle
{
/// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="excelName">文件名称</param>
public static void TableToExcelForXLSX(DataTable dt, string excelName)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("Test");
//表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.ContentType = "application/x-excel";
string filename = HttpUtility.UrlEncode(excelName + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx");
curContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
xssfworkbook.Write(curContext.Response.OutputStream);
curContext.Response.End();
}
/// <summary>
/// 读取excel(版本不低于2007)至DataTable
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt();
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
} /// <summary>
/// 将List导出到Excel
/// </summary>
/// <param name="enList">List数据</param>
/// <param name="fileName">Excel文件名</param>
/// <param name="sheetName">Excel工作表名</param>
/// <param name="cell0Value">首行提示信息</param>
public void IListToExcel( IList enList, string fileName, string sheetName,string cell0Value)
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
sheet.CreateRow().CreateCell().SetCellValue(cell0Value);
List<string> Ihead = new List<string>();
Type types = enList[].GetType();
foreach(var item in types.GetProperties())
{
Ihead.Add(item.Name);
}
IRow row1 = sheet.CreateRow();
for (int i = ; i < Ihead.Count; i++)
{
row1.CreateCell(i).SetCellValue(Ihead[i]);
}
int rowIndex = ;
foreach (var item in enList)
{
IRow rowTmp = sheet.CreateRow(rowIndex);
for (int i = ; i < Ihead.Count; i++)
{
System.Reflection.PropertyInfo properotyInfo = item.GetType().GetProperty(Ihead[i]); // 属性的信息
object properotyValue = properotyInfo.GetValue(item, null);// 属性的值
string cellValue = properotyValue.ToString()??null;// 单元格的值
rowTmp.CreateCell(i).SetCellValue(cellValue);
}
rowIndex++;
}
using (FileStream file = new FileStream(fileName, FileMode.Create))
{
workbook.Write(file);
file.Close();
}
}
}
}
ExcelHandle的更多相关文章
- java的jxl技术导入Excel
项目结构: http://www.cnblogs.com/hongten/gallery/image/112177.html 在项目中我们看到Reference Libraries中的jxl.jar包 ...
- Java实现Excel的操作
JAVA EXCEL API: 开源项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该API非Windows操作系统也可以通过纯Ja ...
- Java生成和操作Excel文件(转载)
Java生成和操作Excel文件 JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该A ...
- OAF_开发系列27_实现OAF中Java类型并发程式开发调用XML Publisher(案例)
20150814 Created By BaoXinjian
- c#.net Excel中的数据导入到SQL数据库中
/// <summary> /// 从Excel 导入学生 /// </summary> /// <param name=&qu ...
- 将数据导入带模板EXCEL
在EXCEL模板里设置好样式和格式 点击事件 private void btnReport_Click(object sender, EventArgs e) { ...
- Java生成和操作Excel文件
JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该API非Windows操作系统也可以通过 ...
- java 操作excel 文件
JAVA EXCEL API:是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容.创建新的Excel文件.更新已经存在的Excel文件.使用该API非Windows操作系统也可以通过 ...
- BIP_开发案例09_结合JavaCP通过BIP API输出报表dataprocess / rtfprocess / foprocess(案例)
20150814 Created By BaoXinjian
随机推荐
- HDU 1159 Common Subsequence 动态规划
2017-08-06 15:41:04 writer:pprp 刚开始学dp,集训的讲的很难,但是还是得自己看,从简单到难,慢慢来(如果哪里有错误欢迎各位大佬指正) 题意如下: 给两个字符串,找到其中 ...
- 监控系统信息模块psutil
About psutil (python system and process utilities) is a cross-platform library for retrieving inform ...
- Springer Latex
What are the guidelines for uploading a LaTeX formatted manuscript? 1. Always upload the main LaTe ...
- 找出此产品描述中包含N个关键字的长度最短的子串
阿里巴巴笔试题:给定一段产品的英文描述,包含M个英文字母,每个英文单词以空格分隔,无其他标点符号:再给定N个英文关键词,请说明思路并变成实现方法. String extractSummary(Stri ...
- python学习笔记(excel中处理日期格式)
涉及到处理excel文件中日期格式数据 这里自己整理下 两种方法 代码如下: @classmethod def get_time(cls, table, nrows): testtime = [] f ...
- easyui datagrid 行编辑功能
datagrid现在具有行编辑能力了,使用时只须在columns中为需要编辑的列添加一个editor属性,编辑保存时同时具有数据校验能力. 看一个例子效果图: 代码如下: $('#tt').datag ...
- 解析session与cookie
Session和Cookie相关概念 Session和Cookie都是有服务器生成的. Session和Cookie都是键值对形式保存,主要用于存储特定的一些状态值. Session保存在服务器,Co ...
- CodeForces 385 D.Bear and Floodlight 状压DP
枚举灯的所有可能状态(亮或者不亮)(1<<20)最多可能的情况有1048576种 dp[i]表示 i 状态时灯所能照射到的最远距离(i 的二进制中如果第j位为0,则表示第j个灯不亮,否则就 ...
- mybatis 批量修改接口的几种实现方式
-----------------我也是有上线的--------------我也是有上线的------------我也是有上线的---------------我也是有上线的-------------- ...
- C# WinForm开发系列之c# 通过.net自带的chart控件绘制饼图,柱形图和折线图的基础使用和扩展
一.需要实现的目标是: 1.将数据绑定到pie的后台数据中,自动生成饼图. 2.生成的饼图有详细文字的说明. 1.设置chart1的属性Legends中默认的Legend1的Enable为false: ...