读取或生成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通用类,可用于读取或生成数据的更多相关文章

  1. 一个完整的类用来读取OpenSSL生成的pem格式的x509证书

    internal static class CcbRsaHelper { private const string Begin = "-----BEGIN "; private c ...

  2. 一个完整的类用来读取OpenSSL生成的pem格式的x509证书(C#)

    internal static class CcbRsaHelper { private const string Begin = "-----BEGIN "; private c ...

  3. 我写了一个java实体类,implements了Serializable接口,然后我如何让serialversionUID自动生成

    写了一个java实体类,implements了Serializable接口,让serialversionUID自动生成方法: 1.点击类旁边的警告符号: 2.选择Add generated seria ...

  4. 同事写了一个疯狂的类构造器,我要疯了,Builder 模式都不会么?!

    疯狂的类构造器 最近栈长在做 Code Review 时,发现一段创建对象的方法: Task task = new Task(112, "紧急任务", "处理一下这个任务 ...

  5. 自己通过反射写的一个属性copy类

    package com.xxx.beancopier; import java.lang.annotation.Documented; import java.lang.annotation.Elem ...

  6. 新手写的一个DBCP工具类

    package com.xx.questionnaire.util.dao; import java.io.IOException; import java.sql.Connection; impor ...

  7. 原生JS写了一个小demo,根据输入的数字生成不同背景颜色的小方块儿~

    昨天练习写了这个小demo,个人觉得通过设置定位元素left和top的值,来实现换行的功能,这种方法很巧妙~ 另外,如下代码中的随机颜色的获取,还请各位前辈多多指教:需要改进的地方:或者有没有更好的方 ...

  8. JavaScript写一个表格排序类

    依稀记得那是上个星期六的下午,我参加了网易暑期实习生招聘笔试.考得相当糟糕,编程题3个题通过了2个,简答题没做对,选择题貌似是20个题猜了6-7个,99%是挂了,唉唉唉!生活不只眼前的苟且,学习的脚步 ...

  9. R入门-第一次写了一个完整的时间序列分析代码

    纪念一下,在心心念念想从会计本科转为数据分析师快两年后,近期终于迈出了使用R的第一步,在参考他人的例子前提下,成功写了几行代码.用成本的角度来说,省去了部门去买昂贵的数据分析软件的金钱和时间,而对自己 ...

随机推荐

  1. python matplotlib

    背景: 1)数据可视化 目前还处于python入门阶段,主要想通过numpy.matplotlib进行数据可视化. 安装: 操作系统:windows7 1)python2.7 安装numpy.matp ...

  2. nodejs express 框架解密5-视图

    本文档是基于express 3.4.6 的 在我们的代码中,渲染模板大致是这样写的 exports.index = function(req, res){ res.render('index', { ...

  3. python数据结构之图的实现

    python数据结构之图的实现,官方有一篇文章介绍,http://www.python.org/doc/essays/graphs.html 下面简要的介绍下: 比如有这么一张图: A -> B ...

  4. 【LeetCode】273. Integer to English Words

    Integer to English Words Convert a non-negative integer to its english words representation. Given i ...

  5. elasticsearch-cn-out-of-box

    elasticsearch-cn-out-of-box https://github.com/hangxin1940/elasticsearch-cn-out-of-box 为elasticsearc ...

  6. Homebrew

    Homebrew官网:http://brew.sh Homebrew installs the stuff you need that Apple didn't Homebrew的安装非常简单,打开终 ...

  7. iOS开发-Xcode升级后插件失效解决办法

    打开terminal,输入如下命令: | xargs -I{} defaults write {} DVTPlugInCompatibilityUUIDs -array-add `defaults r ...

  8. 转:CWnd的函数,以后可以在这儿找了!

    CWnd CObject  └CCmdTarget     └CWnd CWnd类提供了微软基础类库中所有窗口类的基本功能.CWnd对象与Windows的窗口不同,但是两者有紧密联系.CWnd对象是由 ...

  9. HBase 在HDFS 上的目录树

         总所周知,HBase 是天生就是架设在 HDFS 上,在这个分布式文件系统中,HBase 是怎么去构建自己的目录树的呢? 这里只介绍系统级别的目录树. 一.0.94-cdh4.2.1版本 系 ...

  10. Sharepoint 2013列表视图和字段权限扩展插件(免费下载)!

    记得2014年春节期间,有博客园的网友通过QQ向我咨询Sharepoint 2013列表视图和字段权限扩展,因为之前他看到我博客介绍Sharepoint 2010列表视图和字段的权限控制扩展使用,问有 ...