这里向大家介绍一种读取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。

DocumentFormat.OpenXml read excel file的更多相关文章

  1. 使用DocumentFormat.OpenXml操作Excel文件.xlsx

    1.开始 DocumentFormat.OpenXml是ms官方给一个操作office三大件新版文件格式(.xlsx,.docx,.pptx)的组件:特色是它定义了OpenXml所包含的所有对象(たぶ ...

  2. Csharp: read excel file using Open XML SDK 2.5

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  3. csharp:using OpenXml SDK 2.0 and ClosedXML read excel file

    https://openxmlexporttoexcel.codeplex.com/ http://referencesource.microsoft.com/ 引用: using System; u ...

  4. C# 基于DocumentFormat.OpenXml的数据导出到Excel

    using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.S ...

  5. ClosedXML、DocumentFormat.OpenXml导出DataTable到Excel

    在很多系统中都用到导出,使用过多种导出方式,觉得ClosedXML插件的导出简单又方便. 并且ClosedXML.DocumentFormat.OpenXml都是MIT开源. 首先通过 Nuget 安 ...

  6. ExcelDataReader read excel file

    上篇文章向大家介绍了用DocumentFormat.OpenXml.dll读取excel的方法,这里再向大家介绍一种轻量级简便的方法,用的是Excel.dll,及ICSharpCode.SharpZi ...

  7. 一个用微软官方的OpenXml读写Excel 目前网上不太普及的方法。

    新版本的xlsx是使用新的存储格式,貌似是处理过的XML. 传统的excel处理方法,我真的感觉像屎.用Oldeb不方便,用com组件要实际调用excel打开关闭,很容易出现死. 对于OpenXML我 ...

  8. 使用OpenXML将Excel内容读取到DataTable中

    前言:前面的几篇文章简单的介绍了如何使用OpenXML创建Excel文档.由于在平时的工作中需要经常使用到Excel的读写操作,简单的介绍下使用 OpenXML读取Excel中得数据.当然使用Open ...

  9. 用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

随机推荐

  1. 代码解读 | VINS 视觉前端

    本文作者是计算机视觉life公众号成员蔡量力,由于格式问题部分内容显示可能有问题,更好的阅读体验,请查看原文链接:代码解读 | VINS 视觉前端 vins前端概述 在搞清楚VINS前端之前,首先要搞 ...

  2. 12 redis搭建主从服务(ubuntu)

    什么是主从服务 一个master可以拥有多个slave,一个slave可以拥有多个slave,如此下去,形成了多级服务器集群架构 master用来写数据, slave用来读数据, 经统计:网站的读写比 ...

  3. React项目升级遇到的问题复盘(2019-09-02)

    老铁们,发没发现我换了个贼帅的头像,高端大气上档次,非洲大地我最凶!可把我自己牛逼坏了. 不扯啦不扯啦,抓紧进入今天的正题,从今天开始我会每天写一下每天工作的出现的问题,主要对这些问题出现的原因,以及 ...

  4. HTML(三)链接,<head>,css样式

    HTML链接 HTML 超链接 一个未访问过的链接显示为蓝色字体并带有下划线 访问过的链接显示为紫色并带有下划线 点击链接时,链接显示为红色并带有下划线 注意:如果为这些超链接设置了 CSS 样式,展 ...

  5. P1603 斯诺登的密码-字符串加法的妙用

    传送门:https://www.luogu.org/problemnew/show/P1603 题意: 首先在给定的字符串中,找出特定的单词,把它转化成特定的数字, 然后在这些数字中,找出排列结果最小 ...

  6. codeforces E. Okabe and El Psy Kongroo(dp+矩阵快速幂)

    题目链接:http://codeforces.com/contest/821/problem/E 题意:我们现在位于(0,0)处,目标是走到(K,0)处.每一次我们都可以从(x,y)走到(x+1,y- ...

  7. poj 2240 Arbitrage(Bellman_ford变形)

    题目链接:http://poj.org/problem?id=2240 题目就是要通过还钱涨自己的本钱最后还能换回到自己原来的钱种. 就是判一下有没有负环那么就直接用bellman_ford来判断有没 ...

  8. net core天马行空系列: 一个接口多个实现类,利用mixin技术通过自定义服务名,实现精准属性注入

    系列目录 1.net core天马行空系列:原生DI+AOP实现spring boot注解式编程 2.net core天马行空系列: 泛型仓储和声明式事物实现最优雅的crud操作 哈哈哈哈,大家好,我 ...

  9. mybatis转义

    SELECT * FROM test WHERE 1 = 1 AND start_date <= CURRENT_DATE AND end_date >= CURRENT_DATE 在执行 ...

  10. Linux OOM-killer(内存不足时kill高内存进程的策略)

    OOM_killer是Linux自我保护的方式,当内存不足时不至于出现太严重问题,有点壮士断腕的意味 在kernel 2.6,内存不足将唤醒oom_killer,挑出/proc/<pid> ...