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 
随机推荐
- 最大字串和问题(Maximum Subarray)
			问题描述: ind the contiguous subarray within an array (containing at least one number) which has the lar ... 
- java socket - 半关闭
			通常,使用关闭输出流来表示输出已经结束.但在进行网络通信时则不能这样做.因为我们关闭输出流时,该输出流对应的Socket也将随之关闭,这样程序将无法再从该socket中读取数据. 为了应付这种情况,s ... 
- glance cache
			用在多个glance API server 中,对相同的image文件提供服务.该cache对用户透明. 配置文件有一个image_cache_max_size,超过的话image cache会被修剪 ... 
- HTML5标签学习
			<abbr> 表示一个缩写形式,比如 "Inc."."etc.".通过对缩写词语进行标记,您就能够为浏览器.拼写检查程序.翻译系统以及搜索引擎分度器 ... 
- mysql中删除完全重复数据的准确SQL语句
			删除数据库中重复的记录,只保留一条 DELETE FROM tb_gps_records WHERE id NOT IN (SELECT bid FROM (SELECT min(id) as bid ... 
- CPU Usage (C#) 测试
			注意:算法仅供参考. cpuusage.cs using System; using System.Collections.Generic; using System.Diagnostics; usi ... 
- HDU-1007-最小公共点对
			http://acm.hdu.edu.cn/showproblem.php?pid=1007 Quoit Design Time Limit: 10000/5000 MS (Java/Others) ... 
- zzuli  2172  队列优化dp
			2172: GJJ的日常之购物 Time Limit: 3 Sec Memory Limit: 128 MBSubmit: 9 Solved: 8 SubmitStatusWeb Board De ... 
- css中实现显示和隐藏(转)
			CSS中的display和visibility 在平时的开发过程中,总是会遇到一些文字在特定的场景下显示或者隐藏来达到我们想要的效果,css中display和visibility语法,他们都 ... 
- 深入理解c/c++ 内存对齐
			内存对齐,memory alignment.为了提高程序的性能,数据结构(尤其是栈)应该尽可能地在自然边界上对齐.原因在于,为了访问未对齐的内存,处理器需要作两次内存访问:然而,对齐的内存访问仅需要一 ... 
