这里向大家介绍一种读取excel 数据的方法,用的是DoucmentFormat.OpenXml.dll

废话不多说,向大家展示一下在项目中处理过的方法,如果有任何疑问,随时联系我。

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks; namespace EArchivePermissionTool
{
public class ExcelDataReader
{
private bool mIsCheck { get; set; }
public ExcelDataReader(bool mIsCheck)
{
this.mIsCheck = mIsCheck;
}
public Dictionary<string, List<List<string>>> GetWholeSheets(Stream stream)
{
Dictionary<string, List<List<string>>> result = null;
try
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stream, false))
{
result = GetWholeSheets(spreadsheetDocument);
}
}
catch
{ }
finally
{
if (!mIsCheck && stream != null)
{
stream.Dispose();
}
}
return result;
}
private Dictionary<string, List<List<string>>> GetWholeSheets(SpreadsheetDocument spreadsheetDocument)
{
var data = new Dictionary<string, List<List<string>>>();
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
foreach (var worksheetInfo in workbookPart.Workbook.Descendants<Sheet>())
{
if (worksheetInfo.State != null && worksheetInfo.State == SheetStateValues.Hidden)
{
continue;
}
string workSheetName = worksheetInfo.Name;
var sheetData = GetSheetData(workbookPart, (WorksheetPart)workbookPart.GetPartById(worksheetInfo.Id));
data.Add(workSheetName, sheetData);
}
return data;
}
private List<List<string>> GetSheetData(WorkbookPart workbookPart, WorksheetPart worksheetPart)
{
if (worksheetPart == null)
{
throw new Exception("Out of range.");
}
List<List<string>> result = new List<List<string>>();
OpenXmlReader reader = OpenXmlReader.Create(worksheetPart, true);
var rows = worksheetPart.Worksheet.Descendants<Row>();
uint rowIndex = ;
int rowIndexForCheck = ;
foreach (var row in rows)
{
if (row.HasChildren)
{
var currentRowIndex = row.RowIndex.Value;
while (currentRowIndex > rowIndex)
{
result.Add(new List<string>());
++rowIndex; if (mIsCheck)
{
++rowIndexForCheck;
if (rowIndexForCheck == )
{
rowIndexForCheck = ;
break;
}
}
} int columnIndex = ;
List<string> l = new List<string>();
foreach (Cell cell in row.Descendants<Cell>())
{
if (cell.CellReference != null)
{
// Gets the column index of the cell with data
int cellColumnIndex = (int)GetColumnIndexFromName(GetColumnName(cell.CellReference)); if (columnIndex < cellColumnIndex)
{
do
{
l.Add(string.Empty);//Insert blank data here;
columnIndex++;
}
while (columnIndex < cellColumnIndex);
}
}
l.Add(GetCellValue(workbookPart, cell));
columnIndex++;
}
//Changed by EArchive
if (!string.IsNullOrEmpty(l[]))
{
result.Add(l);
}
++rowIndex;
++rowIndexForCheck;
if (mIsCheck && rowIndexForCheck == )
{
break;
}
}
}
return result;
}
/// <summary>
/// Given a cell name, parses the specified cell to get the column name.
/// </summary>
/// <param name="cellReference">Address of the cell (ie. B2)</param>
/// <returns>Column Name (ie. B)</returns>
public static string GetColumnName(string cellReference)
{
// Create a regular expression to match the column name portion of the cell name.
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellReference); return match.Value;
}
/// <summary>
/// Given just the column name (no row index), it will return the zero based column index.
/// Note: This method will only handle columns with a length of up to two (ie. A to Z and AA to ZZ).
/// A length of three can be implemented when needed.
/// </summary>
/// <param name="columnName">Column Name (ie. A or AB)</param>
/// <returns>Zero based index if the conversion was successful; otherwise null</returns>
public static int? GetColumnIndexFromName(string columnName)
{
Regex alpha = new Regex("^[A-Z]+$");
if (!alpha.IsMatch(columnName)) throw new ArgumentException(); char[] colLetters = columnName.ToCharArray();
Array.Reverse(colLetters); int convertedValue = ;
for (int i = ; i < colLetters.Length; i++)
{
char letter = colLetters[i];
int current = i == ? letter - : letter - ; // ASCII 'A' = 65
convertedValue += current * (int)Math.Pow(, i);
}
return convertedValue;
} private string GetCellValue(WorkbookPart workbookPart, Cell c)
{
string cellValue = "";
if (c.CellValue == null)
{
return cellValue;
}
if (c.DataType != null && c.DataType == CellValues.SharedString)
{
SharedStringItem ssi = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(int.Parse(c.CellValue.InnerText));
cellValue = ssi.InnerText;
}
else
{
cellValue = c.CellValue.InnerText;
}
return cellValue.Trim();
} }
}

Note: mIsCheck是一个bool值,初始化为true,只会返回每个sheet的header,初始化为false,返回header及body。

最新文章

  1. BZOJ3198[SDOI2013]SPRING
  2. ASP.NET vNext 概述
  3. css知多少(12)——目录
  4. IOS开发之Bug--遇到一个类型不确定的bug
  5. 在CDH5.5.0上安装Kudu6.0
  6. JSCH实现文件上传的代码实例
  7. uchome 积分体系
  8. MD5Encoder加密支持utf-8
  9. Unity3D自定义地形的笔刷,刷出别样地形
  10. Python 使用心得之--变量命名
  11. Java小白不走弯路学习Java流程以及学习误区
  12. python基础--压缩文件
  13. BZOJ3252攻略——长链剖分+贪心
  14. java中带参数的try(){}语法
  15. [svc]为何linux ext4文件系统目录默认大小是4k?
  16. traceroute 排查 nginx 反向代理 配置
  17. this常见错误
  18. MySQL表类型MyISAM/InnoDB的区别(解决事务不回滚的问题)(转)
  19. python文本 maketrans和translate
  20. 【Java面试题】5 Integer的int 的种种比较?详细分析

热门文章

  1. 18_init 函数的使用
  2. 骑士精神(IDA*)
  3. SpringCloud Feign 之 Fallback初体验
  4. 为什么使用消息队列?消息队列有什么优点和缺点?Kafka、ActiveMQ、RabbitMQ、RocketMQ 都有什么优点和缺点?
  5. 微信公众号之获取openId
  6. hotcss.js Flexible 移动端适配在dpr=2和dpr=3出现的字体大小设置不正确问题.
  7. 【4】Logistic回归
  8. 【LeetCode】116#填充同一层的兄弟节点
  9. Spring MVC中返回JSON数据的几种方式
  10. 开发必配的Finder设置