ExcelHelper
NPOI下载:http://pan.baidu.com/s/1JNAGm
最新封装类:
2016-03-14
1.添加对OleConn的读
private static string connstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" + path + ";Extended Properties=Excel 8.0"; public static DataTable ExecelTable(string sql, params OleDbParameter[] parameter)
{
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand comm = new OleDbCommand(sql, conn))
{
if (parameter != null) comm.Parameters.AddRange(parameter);
if (conn.State == ConnectionState.Closed) conn.Open();
DataTable dt = new DataTable();
OleDbDataAdapter oda = new OleDbDataAdapter(comm);
oda.Fill(dt);
return dt;
}
}
}
2016-04-16
sheet到datatable时候,表中一行是列名
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Web; namespace ssm.Helper
{
public class ExcelHelper
{
#region 导入excel /// <summary>
/// 读取excel路径 生成 DataSet
/// </summary>
/// <param name="path"></param>
public static DataSet GetExcelToDs(string path)
{
DataSet ds = new DataSet();
using (FileStream fs = File.OpenRead(path))
{
using (Workbook wb = new HSSFWorkbook(fs))
{
for (int i = ; i < wb.NumberOfSheets; i++)
{
DataTable dt = ds.Tables[i];
using (Sheet s = wb.CreateSheet())
{
int RowLen = s.LastRowNum;
for (int j = ; j < RowLen; j++)
{
DataRow dr = dt.NewRow();
Row r = s.GetRow(j);
int ColLen = r.LastCellNum;
for (int k = ; k < ColLen; k++)
{
dr[k] = r.GetCell(k);
}
}
}
}
}
}
return ds;
}
public static DataTable GetExcelToDt(string path)
{
DataTable dt = new DataTable();
using (FileStream fs = File.OpenRead(path))
{
using (Workbook wb = new HSSFWorkbook(fs))
{
using (Sheet s = wb.GetSheetAt())
{
Row HeadRow = s.GetRow();
for (int t = ; t < HeadRow.LastCellNum; t++) //set DataTable columns name
{
dt.Columns.Add(HeadRow.GetCell(t).ToString());
} int RowLen = s.LastRowNum;
int ColLen = HeadRow.LastCellNum;
for (int j = ; j < RowLen; j++) // TO DataTable
{
int sheetNum = j + ;
DataRow dr = dt.NewRow();
Row r = s.GetRow(sheetNum); for (int k = ; k < ColLen; k++)
{
// int sheetNum = k + 1; if(r.GetCell(k) != null)
dr[k] = r.GetCell(k); }
dt.Rows.Add(dr);
}
}
}
}
return dt;
}
public static DataTable GetExcelToDt(FileStream fs)
{
DataTable dt = new DataTable();
using (Workbook wb = new HSSFWorkbook(fs))
{
using (Sheet s = wb.GetSheetAt())
{
Row HeadRow = s.GetRow();
for (int t = ; t < HeadRow.LastCellNum; t++) //set DataTable columns name
{
dt.Columns.Add(HeadRow.GetCell(t).ToString());
} int RowLen = s.LastRowNum;
for (int j = ; j < RowLen; j++) // TO DataTable
{
DataRow dr = dt.NewRow();
Row r = s.GetRow(j);
int ColLen = r.LastCellNum;
for (int k = ; k < ColLen; k++)
{
dr[k] = r.GetCell(k);
}
dt.Rows.Add(dr);
}
}
}
return dt;
}
#endregion #region 导出excel
/// <summary>
/// 表转化成excel并且下载
/// </summary>
/// <param name="dt">表</param>
/// <param name="title">文件名</param>
public static void CreateExcelToDown(DataTable dt, string title)
{
using (Workbook book = new HSSFWorkbook())
{
Sheet sheet = book.CreateSheet("sheet1"); Row headerrow = sheet.CreateRow();
CellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER;
//1.转化表头
for (int i = ; i < dt.Columns.Count; i++)
{
Cell cell = headerrow.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//2.填写数据
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = sheet.CreateRow((i+));
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
//3.下载
using (MemoryStream ms = new MemoryStream())
{
book.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
}
}
public static void CreateExcelToDown<T>(List<T> lt , string title)
{
Type type = lt.GetType();
PropertyInfo[] pi = type.GetProperties(); using (Workbook book = new HSSFWorkbook())
{
Sheet sheet = book.CreateSheet("sheet1"); Row headerrow = sheet.CreateRow();
CellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER; //1.转化表头
for (int i = ; i < pi.Length; i++)
{
Cell cell = headerrow.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(pi[i].Name);
}
//2.填写数据
int RowLen = lt.Count; // get List<> count
int ColLen = pi.Length; // get proper length //3.下载
using (MemoryStream ms = new MemoryStream())
{
book.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// DataSet 创建生成 excel文件,保存到本地
/// </summary>
/// <param name="name"></param>
/// <param name="ds"></param>
public static bool CreateExcelToFile(string name, DataSet ds)
{
bool isValue = false;
int DsLen = ds.Tables.Count;
using (Workbook wk = new HSSFWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
using (FileStream fs = File.OpenWrite(System.Web.HttpContext.Current.Server.MapPath(name + @".xls")))
{
wk.Write(fs);
}
}
}
isValue = true;
}
return isValue;
} /// <summary>
/// DataTable创建生成Excel,保存到本地
/// </summary>
/// <param name="name"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool CreateExcelToFile(string name, DataTable dt)
{
bool isValue = false;
using (Workbook wk = new HSSFWorkbook())
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
using (FileStream fs = File.OpenWrite(System.Web.HttpContext.Current.Server.MapPath(name + @".xls")))
{
wk.Write(fs);
}
}
isValue = true;
}
return isValue;
} /// <summary>
///error DataTable 创建生成 Excel ,生成文件流
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static MemoryStream CreateExcelToStream(DataTable dt)
{
using (Workbook wk = new HSSFWorkbook())
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
MemoryStream ms = new MemoryStream();
wk.Write(ms);
return ms;
}
}
}
#endregion } }
2016-05-11
修改4.16问题:表中一行是列名
public class ExcelHelper
{
#region 导入excel /// <summary>
/// 读取excel路径 生成 DataSet
/// </summary>
/// <param name="path"></param>
public static DataSet GetExcelToDs(string path)
{
DataSet ds = new DataSet();
using (FileStream fs = File.OpenRead(path))
{
using (Workbook wb = new HSSFWorkbook(fs))
{
for (int i = ; i < wb.NumberOfSheets; i++)
{
DataTable dt = ds.Tables[i];
using (Sheet s = wb.CreateSheet())
{
int RowLen = s.LastRowNum;
for (int j = ; j < RowLen; j++)
{
DataRow dr = dt.NewRow();
Row r = s.GetRow(j);
int ColLen = r.LastCellNum;
for (int k = ; k < ColLen; k++)
{
dr[k] = r.GetCell(k);
}
}
}
}
}
}
return ds;
}
public static DataTable GetExcelToDt(string path)
{
DataTable dt = new DataTable();
using (FileStream fs = File.OpenRead(path))
{
using (Workbook wb = new HSSFWorkbook(fs))
{
using (Sheet s = wb.GetSheetAt())
{
Row HeadRow = s.GetRow();
for (int t = ; t < HeadRow.LastCellNum; t++) //set DataTable columns name
{
dt.Columns.Add(HeadRow.GetCell(t).ToString());
} int RowLen = s.LastRowNum;
int ColLen = HeadRow.LastCellNum;
for (int j = ; j < RowLen; j++) // TO DataTable
{
int sheetNum = j + ;
DataRow dr = dt.NewRow();
Row r = s.GetRow(sheetNum); for (int k = ; k < ColLen; k++)
{
// int sheetNum = k + 1; if(r.GetCell(k) != null)
dr[k] = r.GetCell(k); }
dt.Rows.Add(dr);
}
}
}
}
return dt;
}
public static DataTable GetExcelToDt(FileStream fs)
{
DataTable dt = new DataTable();
using (Workbook wb = new HSSFWorkbook(fs))
{
using (Sheet s = wb.GetSheetAt())
{
Row HeadRow = s.GetRow();
for (int t = ; t < HeadRow.LastCellNum; t++) //set DataTable columns name
{
dt.Columns.Add(HeadRow.GetCell(t).ToString());
} int RowLen = s.LastRowNum;
for (int j = ; j < RowLen; j++) // TO DataTable
{
DataRow dr = dt.NewRow();
Row r = s.GetRow(j);
int ColLen = r.LastCellNum;
for (int k = ; k < ColLen; k++)
{
dr[k] = r.GetCell(k);
}
dt.Rows.Add(dr);
}
}
}
return dt;
}
#endregion #region 导出excel
/// <summary>
/// 表转化成excel并且下载
/// </summary>
/// <param name="dt">表</param>
/// <param name="title">文件名</param>
public static void CreateExcelToDown(DataTable dt, string title)
{
using (Workbook book = new HSSFWorkbook())
{
Sheet sheet = book.CreateSheet("sheet1"); Row headerrow = sheet.CreateRow();
CellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER;
//1.转化表头
for (int i = ; i < dt.Columns.Count; i++)
{
Cell cell = headerrow.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//2.填写数据
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = sheet.CreateRow((i+));
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
//3.下载
using (MemoryStream ms = new MemoryStream())
{
book.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
}
}
public static void CreateExcelToDown<T>(List<T> lt , string title)
{
Type type = lt.GetType();
PropertyInfo[] pi = type.GetProperties(); using (Workbook book = new HSSFWorkbook())
{
Sheet sheet = book.CreateSheet("sheet1"); Row headerrow = sheet.CreateRow();
CellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER; //1.转化表头
for (int i = ; i < pi.Length; i++)
{
Cell cell = headerrow.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(pi[i].Name);
}
//2.填写数据
int RowLen = lt.Count; // get List<> count
int ColLen = pi.Length; // get proper length //3.下载
using (MemoryStream ms = new MemoryStream())
{
book.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// DataSet 创建生成 excel文件,保存到本地
/// </summary>
/// <param name="name"></param>
/// <param name="ds"></param>
public static bool CreateExcelToFile(string name, DataSet ds)
{
bool isValue = false;
int DsLen = ds.Tables.Count;
using (Workbook wk = new HSSFWorkbook())
{
foreach (DataTable dt in ds.Tables)
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
using (FileStream fs = File.OpenWrite(System.Web.HttpContext.Current.Server.MapPath(name + @".xls")))
{
wk.Write(fs);
}
}
}
isValue = true;
}
return isValue;
} /// <summary>
/// DataTable创建生成Excel,保存到本地
/// </summary>
/// <param name="name"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static bool CreateExcelToFile(string name, DataTable dt)
{
bool isValue = false;
using (Workbook wk = new HSSFWorkbook())
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
using (FileStream fs = File.OpenWrite(System.Web.HttpContext.Current.Server.MapPath(name + @".xls")))
{
wk.Write(fs);
}
}
isValue = true;
}
return isValue;
} /// <summary>
///error DataTable 创建生成 Excel ,生成文件流
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static MemoryStream CreateExcelToStream(DataTable dt)
{
using (Workbook wk = new HSSFWorkbook())
{
using (Sheet s = wk.CreateSheet())
{
int RowLen = dt.Rows.Count;
int ColLen = dt.Columns.Count;
for (int i = ; i < RowLen; i++)
{
DataRow dr = dt.Rows[i];
Row r = s.CreateRow(i);
for (int j = ; j < ColLen; j++)
{
r.CreateCell(j).SetCellValue(dr[j].ToString());
}
}
MemoryStream ms = new MemoryStream();
wk.Write(ms);
return ms;
}
}
}
#endregion }
2016.5.11
增加一个按模型类导出EXCEL的方法:
public string CreateExcelDown<T>(string Title, List<T> lt)
{
//用来分行色的
string color = "";
int num = ; StringBuilder sb = new StringBuilder();
Type type = typeof(T);
PropertyInfo[] pi = type.GetProperties(); //生成表头
sb.Append(@"<table style=""width:900px;"" cellpadding=""2"" cellspacing=""0"" align=""center"" border=""1"" bordercolor=""#000000"">");
sb.Append("<tbody> <tr>"); sb.Append(@" <td colspan=""" + pi.Count() + @""" style=""text-align:center;""><h2>");
sb.Append(Title);
sb.Append("</h2></td>");
sb.Append("</tr>"); //生成列名
sb.Append("<tr>");
foreach (var p in pi)
{
sb.Append(@"<td style=""text-align:center;""><h4>" + p.Name + "</h4></td>");
}
sb.Append("</tr>"); //输入内容
foreach (var m in lt)
{
if ((num++) % == )
color = "background-color:#FFE500";
else
color = "";
sb.Append("<tr>");
foreach (var i in pi)
{
sb.AppendFormat(@"<td style=""text-align:center;{0}"">{1}</td>", color, i.GetValue(m, null));
}
sb.Append("</tr>");
} sb.Append("</tbody></table>"); return sb.ToString();
}
public string CreateExcelDown<T>(string Title, List<T> lt)
Title 表名,List<T> lt:你要用到的List集合
上面只是生成HTML,如果要下载还需要实习以下代码(MVC中):
public FileResult DownBmxx(bmmanVm s)
{
//1.获取信息表
List<bmmanVm> si = zsglBLL.GetBmMan(MyCookie.Read()); //2.剔除不要信息,只是给你做
if (s.DateTime != )
si = si.Where(x => x.DateTime == s.DateTime).ToList();
if (s.RecommName != null)
si = si.Where(x => x.RecommName == s.RecommName).ToList();
if (s.Card != null)
si = si.Where(x => x.Card.Contains(s.Card)).ToList();
if (s.Name != null)
si = si.Where(x => x.Name.Contains(s.Name)).ToList();
if (s.MajorName != null)
si = si.Where(x => x.MajorName.Contains(s.MajorName)).ToList();
if (s.SchoolName != null)
si = si.Where(x => x.SchoolName.Contains(s.SchoolName)).ToList(); //3.生成excel模型表
int i = ;
List<outBmxxExcelVm> lo = si.Select(x
=> new outBmxxExcelVm {
专业名=x.MajorName,
入学时间=x.DateTime,
姓名=x.Name,
学校名=x.SchoolName,
层次=x.lv,
类型=x.fm,
编号=i++,
负责人=x.RecommName
})
.ToList(); //4.生成下载流
string html = CreateExcelDown("招生信息表", lo);
byte[] fileContents = Encoding.Default.GetBytes(html); //5.文件流下载
return File(fileContents, "application/ms-excel", "招生信息表.xls");
ExcelHelper的更多相关文章
- C#EXCEL 操作类--C#ExcelHelper操作类
主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Excel文件5.将指定的集合数据导出至Exce ...
- 我写的一个ExcelHelper通用类,可用于读取或生成数据
读取或生成EXCEL数据的方法有很多,一般常见的有: 1.通过OFFICE EXCEL组件,优点:读取与生成EXCEL文件方便,缺点:服务器上必须安装OFFICE软件,且进程无法及时释放 2.通过第三 ...
- Excel导入数据(97--2003版本)的ExcelHelper
首先确定excel的版本为97~2003版本 其次创建一个帮助类——ExcelHelper //单个sheet public static DataTable AnalysisExcel(string ...
- 【转】ExcelHelper类,用npoi读取Excel文档
//------------------------------------------------------------------------------------- // All Right ...
- [Excel] C# ExcelHelper操作类 (转载)
点击下载 ExcelHelper.rar 主要功能如下1.导出Excel文件,自动返回可下载的文件流 2.导出Excel文件,转换为可读模式3.导出Excel文件,并自定义文件名4.将数据导出至Exc ...
- 基于NPOI开源框架写的ExcelHelper【转载】
namespace ExcelTest { using System; using System.Collections.Generic; using System.Data; using Syste ...
- ExcelHelper Excel,Export,Import
using System; using System.Collections.Generic; using System.Data; using System.Data.Odbc; using Sys ...
- C# ExcelHelper
using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...
- x01.ExcelHelper: NPOI 操作
Excel 操作,具有十分明显的针对性,故很难通用,但这并不妨碍参考后以解决自己的实际问题. 有一汇总表如下: 当然,只是示范,产品的代码应该唯一!现在要根据此汇总表产生各个客户的产品清单.由于客户较 ...
随机推荐
- 约瑟夫环问题分析-C语言经典面试题
好久没有看有关算法的问题了,今天废了不少劲,再感叹一句:要想学好算法就要常练习,没什么捷径可走.废话不多说,如下: 问题描述:有m个人,围成一个环,编号为 0.1.2.3...m-1,从第一个人开始循 ...
- FMDB的简单使用
1.什么是FMDB? FMDB是iOS平台的SQLite数据库框架 FMDB以OC的方式封装了SQLite的C语言API. 无论项目中使用 ARC 还是 MRC,对 FMDB 都没有任何影响,FMDB ...
- eclipse中配置dtd和xsd文件实现自动提示
DTD 类型约束文件 1. Window->Preferences->XML->XML Catalog->User Specified Entries窗口中,选择Ad ...
- 结对编程-地铁续(有种上个学期OO的既视感)
我们组比较特殊..三人结对 github:https://github.com/qingchanghan/WPFUI_Metro po一张照片: 石浩然,韩青长.陈彦吉 (台式机真的很高端,分屏贼帅) ...
- 字符输入流Reader简要概括
字符输入流Reader组成结构 本篇将对JAVA I/O流中的字符输入流Reader做个简单的概括: 总得来说,每个字符输入流类都有一个对应的用途,如下: 字符流基类:Reader 字节流转字符流:I ...
- adroid 目录
安桌程式安装后存在目录:\手机存储\Android\data 一: // 获取当前程序路径 getApplicationContext().getFilesDir().getAbsolutePath ...
- MYSQL:使用\G参数改变输出结果集的显示方式
在mysql命令行工具中执行查询时,当表的列很多的时候显示很乱. 上面的显示你肯定看不清楚吧.以上方式是默认以列(表格)形式显示的.那怎么以行(表单)的方式显示呢,请看下面 OK,搞定. 参考文档:h ...
- JS MD5
1 /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as ...
- vim IDE平台-打造属于自己的配置
vim IDE平台-打造属于自己的配置 一.前言 目前工作环境基本以Linux为主,自然用到VIM也很多,很早就对如何提高VIM的使用效率有所研究,限于时间关系,也没做个系统记录和资料积累,时间久了又 ...
- shell编程入门
背景知识 Shell 是用户与内核进行交互操作的一种接口,是 Linux 最重要的软件之一.目前最流行的 Shell 称为 bash Shell,bash Shell 脚本编程以其简洁.高效而著称,多 ...