读取或生成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. quartzScheduler_Worker-1] but has failed to stop it. This is very likely to create a memory leak解决

    01-Jul-2016 07:24:20.218 INFO [main] org.apache.catalina.startup.Catalina.start Server startup in 80 ...

  2. MinStack

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  3. mybatis热加载的实现

    最近在使用mybatis,由于是刚刚开始用,用的并不顺手,目前是感觉有2个地方非常的不好用: 1.mybatis调试不方便 由于dao层只有接口,实现只是一个map的xml文件,想加断点都没有地方加, ...

  4. pip install使用豆瓣源

    这个是老问题了 pip install -i https://pypi.douban.com/simple/ selenium 类似的,npm和gem安装的时候可以使用淘宝源.

  5. Nagios 安装配置

    ##Debian 6 安装server # apt-get install nagios* 一路设置好各种密码,成功后访问 http://ip/nagios3 既可,默认用户*nagiosadmin* ...

  6. LCLFramework架构必须要知道的知识

    技术实现: 代码是否面向对象,要看你的继承怎么用 用抽象来展现层次感 用接口来制定操作的统一性 依赖住入(Inversion of Control) Unit of Work Repository D ...

  7. 转:windows下多线程通信方法

    多线程知识简介 同一进程中可以包含多个线程,由于进程中的多个线程可以共享进程中的资源,所以使同一进程中的多个线程之间通信相对比较简单. 当需要有多个线程来访问一个全局变量时,通常我们会在这个全局变量前 ...

  8. C++的黑科技

    周二面了腾讯,之前只投了TST内推,貌似就是TST面试了 其中有一个问题,"如何产生一个不能被继承的类",这道题我反反复复只想到,将父类的构造函数私有,让子类不能调用,最后归结出一 ...

  9. Intellij IDEA IDE部署Servlet项目

    1.设置Project Structure 2.修改Modules中的Web项目文件默认class编译之后输出位置 3.给Modules中的Web项目添加Web模块 4.修改Web项目Web.xml文 ...

  10. httpwebrequest 服务器提交了协议冲突. section=responsestatusline

    调用接口的时候,包: httpwebrequest 服务器提交了协议冲突. section=responsestatusline 解决方案: req.KeepAlive = false; req.Al ...