读取或生成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. php生成UUID

    UUID含义是 通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, O ...

  2. Linux 磁带机备份完全攻略

    一.确定数据备份策略 首先必须确定在备份过程中操作哪些文件.在商业环境中,这是非常困难的一个决定,而且会产生严重的影响.如果备份了太多数据,会导致备份系统的成本过于庞大,会削减其他方面的开支.如果没有 ...

  3. 推荐算法——距离算法

    本文内容 用户评分表 曼哈顿(Manhattan)距离 欧式(Euclidean)距离 余弦相似度(cos simliarity) 推荐算法以及数据挖掘算法,计算"距离"是必须的~ ...

  4. YAFFS2文件系统分析(转)

    http://blog.chinaunix.net/uid-25314474-id-343665.html 1.前言略. 2.yaffs 文件系统简介按理说这里应该出现一些诸如“yaffs 是一种适合 ...

  5. liunx CentOS 升级Python版本

    CentOS python版本是V2.6.6,升级3.4.3. 1.下载 安装包:wget http://www.python.org/ftp/python/3.4.3/Python-3.4.3.tg ...

  6. 手动安装 atom 扩展包 packages

    由于某些原因, 我们下载 atom 扩展时发现速度特别慢, 或者根本无法下载, 那我们可以尝试手动安装 首先, 从 github 上下载(或其它地方) 扩展包, 解压 进入该文件夹, 找到 packa ...

  7. TypeError: Cannot read property 'root' of null

    解决办法: brew upgrade watchman

  8. 算法 - 求两个自然数的最小公倍数(C++)

    //************************************************************************************************** ...

  9. yii2高级应用

    public function searchWithRelated() {         $criteria = new CDbCriteria; $criteria->together = ...

  10. Log4Net简单使用

    一. Log4net是什么.优点 用来记录程序日志,优点:1.提供应用程序运行时的精确环境,可供开发人员尽快找到应用程序中的Bug:2.日志信息可以输出到不同的地方(数据库,文件,邮箱等). 二. L ...