我写的一个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的第一步,在参考他人的例子前提下,成功写了几行代码.用成本的角度来说,省去了部门去买昂贵的数据分析软件的金钱和时间,而对自己 ...
随机推荐
- 防止ViewPager中的Fragment被销毁的方法,更加流畅
在使用ViewPager与Fragment的时候,ViewPager会自动缓存1页内的数据,如下图: 当我们当前处在页面2的时候,页面1和页面3的View实际上已经创建好了,所以在我们拖动的时候是可以 ...
- Unity3D Shader入门指南(一)
动机 自己使用Unity3D也有一段时间了,但是很多时候是流于表面,更多地是把这个引擎简单地用作脚本控制,而对更深入一些的层次几乎没有了解.虽然说Unity引擎设计的初衷就是创建简单的不需要开发者操心 ...
- win7下虚拟机安装mac 转载自 http://itbbs.pconline.com.cn/50602805.html
最近,不断有人问起,如何在vmware下安装MAC系统.起因是以前曾发过一篇贴,在vmware8下安装MAC的方法.于是,重新下载了最新版苹果系统10.8.5,终于成功安装.现将注意事项及过程与各位朋 ...
- Scala 深入浅出实战经典 第45讲: scala中context bounds代码实例
王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...
- [LeetCode] Longest Increasing Subsequence
Longest Increasing Subsequence Given an unsorted array of integers, find the length of longest incre ...
- java代写
Computer Science, Claremont McKenna CollegeCS51.2 - Introduction to Computer Science, Fall 2014Probl ...
- php 生成 Json
php 生成 Json 部分 <?php $arr_result = array(); //返回值 $arr_result['result'] = '0'; $arr_result['calle ...
- post 的body json要使用双引号,而不是单引号
string parse error , JS eval error {'name' : 'wade' } http://json.parser.online.fr/ string parse ...
- 【工作代码】复杂 JSON 值替换处理
总结下最近的工作遇到的点:入参复杂 JSON 层层嵌套,Java 怎么优雅的处理. 一.关于 JSON JSON 是类似 XML 用于存储和交互文本信息.但优于 XML ,其更小,更快,更易懂和解析. ...
- jquery-migrate.js
这个插件可以用来检测和恢复在jQuery1.9版本中已删除或已过时的API.