我写的一个ExcelHelper通用类,可用于读取或生成数据
读取或生成EXCEL数据的方法有很多,一般常见的有:
1.通过OFFICE EXCEL组件,优点:读取与生成EXCEL文件方便,缺点:服务器上必须安装OFFICE软件,且进程无法及时释放
2.通过第三方组件(比如:NPOI),优点:无需安装OFFICE软件,缺点:需要引入第三方组件,当然这个还是比较强的
3.通过把EXCEL当成数据库,连接后运用SQL语句读取,写入的话就自行拼接成HTML表格,优点:无需另外的组件,缺点:需要会SQL及拼接HTML表格较麻烦;
三种方法我都有用过,若开发BS网站程序,建议采用第二种、第三种方法,若开发CS结构,建议采用第一种或第二种;
以下是我针对BS端写的一个ExcelHelper通用类,可用于读取或生成数据,比较方便,技术原理是上述的第三种方法,代码如下,可能存在缺陷,高手见谅:
namespace ASOTS.Models
{
public abstract class ExcelHelper
{
/// <summary>
/// 获取EXCEL中指定sheet内容
/// </summary>
/// <returns></returns>
public static DataTable GetTableFromExcel(string filePath, string fileExt, string tableName, int colsCount)
{
string connstr = null;
if (fileExt == ".xls")
{
connstr = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
}
else
{
connstr = "Provider = Microsoft.ACE.OLEDB.12.0 ; Data Source =" + filePath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
} using (OleDbConnection excelConn = new OleDbConnection(connstr))
{
excelConn.Open(); //获取EXCEL架构信息
DataTable schemaTable = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" }); //判断指定sheet名是否存在
DataView schemaView = new DataView(schemaTable);
schemaView.RowFilter = "TABLE_NAME='" + tableName + "$'";
schemaTable = schemaView.ToTable(); if (schemaTable != null && schemaTable.Rows.Count > )
{
DataTable schemaTable_Cols = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, tableName + "$", null });
schemaView = new DataView(schemaTable_Cols);
schemaView.RowFilter = "ORDINAL_POSITION<=" + colsCount.ToString();
schemaView.Sort = "ORDINAL_POSITION asc";
schemaTable_Cols = schemaView.ToTable();
string selectCols = "";
for (int i = ; i < schemaTable_Cols.Rows.Count; i++)
{
selectCols += "," + schemaTable_Cols.Rows[i]["COLUMN_NAME"].ToString();
} selectCols = selectCols.Substring(); //查询sheet中的数据
string strSql = "select " + selectCols + " from [" + tableName + "$]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, excelConn);
DataSet ds = new DataSet();
da.Fill(ds, tableName);
excelConn.Close();
return ds.Tables[tableName];
}
else
{
excelConn.Close();
return null;
}
} } /// <summary>
/// 将数据模型集合对象生成HTML表格字符串
/// </summary>
/// <param name="data"></param>
/// <param name="tableAttributes"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static string SetDataToHtmlTable(IEnumerable data, string tableAttributes, params KeyValuePair<string, string>[] headers)
{
StringBuilder htmlTableBuilder = new StringBuilder();
htmlTableBuilder.AppendFormat("<table {0}>", tableAttributes); if (data.GetEnumerator().Current == null)
{
throw new Exception("没有获取到任何数据!");
} Type t = data.GetEnumerator().Current.GetType(); string[] cellIndexs = new string[headers.Count()]; htmlTableBuilder.Append("<tr>");
for (int i = ; i < headers.Count(); i++)
{
cellIndexs[i] = headers[i].Key;
htmlTableBuilder.AppendFormat("<th>{0}</th>", headers[i].Value);
}
htmlTableBuilder.Append("</tr>"); foreach (var item in data)
{
htmlTableBuilder.Append("<tr>");
for (int i = ; i < cellIndexs.Length; i++)
{
object pValue = t.GetProperty(cellIndexs[i]).GetValue(item, null);
htmlTableBuilder.AppendFormat("<td>{0}</td>", pValue);
}
htmlTableBuilder.Append("</tr>");
} htmlTableBuilder.Append("</table>"); return htmlTableBuilder.ToString();
} /// <summary>
/// 将DataTable对象生成HTML表格字符串
/// </summary>
/// <param name="data"></param>
/// <param name="tableAttributes"></param>
/// <param name="headers"></param>
/// <returns></returns>
public static string SetDataToHtmlTable(DataTable dataTable, string tableAttributes, params KeyValuePair<string, string>[] headers)
{
StringBuilder htmlTableBuilder = new StringBuilder();
htmlTableBuilder.AppendFormat("<table {0}>", tableAttributes); htmlTableBuilder.Append("<tr>");
for (int i = ; i < headers.Count(); i++)
{
htmlTableBuilder.AppendFormat("<th>{0}</th>", headers[i].Value);
}
htmlTableBuilder.Append("</tr>"); foreach (DataRow row in dataTable.Rows)
{
htmlTableBuilder.Append("<tr>");
for (int i = ; i < headers.Count(); i++)
{
htmlTableBuilder.AppendFormat("<td>{0}</td>", row[headers[i].Key]);
}
htmlTableBuilder.Append("</tr>");
} htmlTableBuilder.Append("</table>"); return htmlTableBuilder.ToString();
} } public class KeyValueList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
public void Add(TKey key, TValue value)
{
base.Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
}
调用方法如下:
//读数据
DataTable resultTable = ExcelHelper.GetTableFromExcel(saveFilePath, fileExt, "data", ); //生成表格(以下是MVC调用,WEBFORM同理)
KeyValueList<string, string> headers = new KeyValueList<string, string>() {
{"year","年 份"},
{"month","月 份"},
{"stage1count","一 阶"},
{"stage2count","二 阶"},
{"stage3count","三 阶"},
{"stage4count","四 阶"},
{"yearincount","一年内进厂"},
{"stagetotalcount","基盘客户总数"},
{"stage1rate","一阶占比"},
{"stage2rate","二阶占比"},
{"stage3rate","三阶占比"},
{"stage4rate","四阶占比"}
}; string tableAttributes = "border='1' cellspacing='3' cellpadding='3'"; string htmlTable=ExcelHelper.SetDataToHtmlTable(model, tableAttributes, headers.ToArray());
byte[] b = System.Text.Encoding.UTF8.GetBytes(htmlTable); return File(b, "application/vnd.ms-excel", string.Format("StageSummary_{0}_{1}_{2}.xls",orgcode,startym,endym));
其中:KeyValueList是我创建的一个集合类,主要用于生成表头,以及表头与数据列对应,之所以写成类,是因为若直接使用:List<KeyValuePair<TKey, TValue>>,则无法直接使用集合初始化器,就必需得一个一个的添加对象,有些繁琐,增加了ADD方法后,就可以直接用:new KeyValueList<string, string>() {{"",""},...}很方便,有人可能说为什么不用SortedDictionary等现有排序类,原因是SortedDictionary是基于Key排序,而此处是采用ADD的先后顺序来固定顺序的。
更多IT相关资讯与技术文章,欢迎光临我的个人网站:http://www.zuowenjun.cn/
我写的一个ExcelHelper通用类,可用于读取或生成数据的更多相关文章
- 一个完整的类用来读取OpenSSL生成的pem格式的x509证书
internal static class CcbRsaHelper { private const string Begin = "-----BEGIN "; private c ...
- 一个完整的类用来读取OpenSSL生成的pem格式的x509证书(C#)
internal static class CcbRsaHelper { private const string Begin = "-----BEGIN "; private c ...
- 我写了一个java实体类,implements了Serializable接口,然后我如何让serialversionUID自动生成
写了一个java实体类,implements了Serializable接口,让serialversionUID自动生成方法: 1.点击类旁边的警告符号: 2.选择Add generated seria ...
- 同事写了一个疯狂的类构造器,我要疯了,Builder 模式都不会么?!
疯狂的类构造器 最近栈长在做 Code Review 时,发现一段创建对象的方法: Task task = new Task(112, "紧急任务", "处理一下这个任务 ...
- 自己通过反射写的一个属性copy类
package com.xxx.beancopier; import java.lang.annotation.Documented; import java.lang.annotation.Elem ...
- 新手写的一个DBCP工具类
package com.xx.questionnaire.util.dao; import java.io.IOException; import java.sql.Connection; impor ...
- 原生JS写了一个小demo,根据输入的数字生成不同背景颜色的小方块儿~
昨天练习写了这个小demo,个人觉得通过设置定位元素left和top的值,来实现换行的功能,这种方法很巧妙~ 另外,如下代码中的随机颜色的获取,还请各位前辈多多指教:需要改进的地方:或者有没有更好的方 ...
- JavaScript写一个表格排序类
依稀记得那是上个星期六的下午,我参加了网易暑期实习生招聘笔试.考得相当糟糕,编程题3个题通过了2个,简答题没做对,选择题貌似是20个题猜了6-7个,99%是挂了,唉唉唉!生活不只眼前的苟且,学习的脚步 ...
- R入门-第一次写了一个完整的时间序列分析代码
纪念一下,在心心念念想从会计本科转为数据分析师快两年后,近期终于迈出了使用R的第一步,在参考他人的例子前提下,成功写了几行代码.用成本的角度来说,省去了部门去买昂贵的数据分析软件的金钱和时间,而对自己 ...
随机推荐
- Spring 4.3.2下实现http多次断点下载
其实跟 spring 无关,如果是直接下载资源很多 web sever 不用程序就直接实现了断点. 但我们的应用是 download?url=xxxx 这种方式 下载资源由 download 来负责, ...
- [算法导论]二叉查找树的实现 @ Python
<算法导论>第三版的BST(二叉查找树)的实现: class Tree: def __init__(self): self.root = None # Definition for a b ...
- Objective-C中将结构体与联合体封装为NSValue对象
在Clang 3.7之前,Objective-C已经可以使用类似@100.@YES.@10.5f等字面量表示一个NSNumber对象:用类似@"xxx"的字面量表示一个NSStri ...
- LINUX系统下添加映射存储LUN
LINUX系统下添加映射存储LUN(无需重启) 背景:Oracle rac环境 添加新实例,重新划分存储空间,从存储映射新的LUN. 问题:映射后,linux操作系统无法识别新的LUN,不能重启系统, ...
- C#打开摄像头抓取照片然后退出
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespa ...
- 如何升级TeX Live 2014宏包
转:人大经济论坛 LATEX论坛 版,详细出处参考: http://bbs.pinggu.org/forum.php?mod=viewthread&tid=3370640&page=1 ...
- Xcode 8 新特性
在2016 苹果全球开发者大会(WWDC)期间, 苹果一如既往地给开发者们披露了新版的集成开发工具 – Xcode, 在过去的每一次大版本发布中,苹果都会积极地改进开发工具,添加一些极具吸引力的新功能 ...
- LoadRunner 12 发布,主推云
LoadRunner 12 发布,主推云 http://blog.csdn.net/testing_is_believing/article/details/22572341
- ITSEC TEAM 2013培训公开视频
信息安全·WEB安全培训 - 做最靠谱的WEB安全培训网站 http://edu.itsec.pw/ ITSEC TEAM 2013公开课视频 包含XSS.CCNA 视频截图: 视频连接:http: ...
- js 当前日期增加自然月
js 在日期不满足的情况下就会自动加1个月,比如在当前时间为3月31号,传入1,1两个参数,预期结果为2月29日,但是结果输出了3月2日.就是如果不满就会溢出到下个月,后来看了api发现了setMon ...