using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.IO;
using System.Xml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml; namespace ECLink.Common
{
/// <summary>
/// 采用openxml方式把excel转换成DataSet
/// </summary>
public class ExcelHelper
{
public ExcelHelper()
{ }
/// <summary>
/// 将Excel多单一表转化为DataSet数据集对象
/// </summary>
/// <param name="filePath">Excel文件路径</param>
/// <returns>转化的数据集</returns>
public DataSet ExcelToDataSet(string filePath)
{
DataSet dataSet = new DataSet();
try
{
using (SpreadsheetDocument spreadDocument = SpreadsheetDocument.Open(filePath, false))
{
//指定WorkbookPart对象
WorkbookPart workBookPart = spreadDocument.WorkbookPart;
//获取Excel中SheetName集合
List<string> sheetNames = GetSheetNames(workBookPart); foreach (string sheetName in sheetNames)
{
DataTable dataTable = WorkSheetToTable(workBookPart, sheetName);
if (dataTable != null)
{
dataSet.Tables.Add(dataTable);//将表添加到数据集
}
}
}
}
catch (Exception exp)
{
throw new Exception("可能Excel正在打开中,请关闭重新操作!");
}
return dataSet;
} /// <summary>
/// 根据WorkbookPart和表名创建DataTable对象
/// </summary>
/// <param name="workBookPart">WorkbookPart对象</param>
/// <param name="tableName">表名</param>
/// <returns>转化后的DataTable</returns>
public DataTable WorkSheetToTable(WorkbookPart workBookPart, string sheetName)
{
//创建Table
DataTable dataTable = new DataTable(sheetName); //根据WorkbookPart和sheetName获取该Sheet下所有行数据
IEnumerable<Row> sheetRows = GetWorkBookPartRows(workBookPart, sheetName);
IEnumerable<Column> sheetColumns = GetWorkBookPartColumns(workBookPart, sheetName); if (sheetRows == null || sheetRows.Count() <= )
{
return null;
} SharedStringTable stringTable = workBookPart.SharedStringTablePart.SharedStringTable;
//将数据导入DataTable,假定第一行为列名,第二行以后为数据
foreach (Row row in sheetRows)
{
//获取Excel中的列头
if (row.RowIndex == )
{
GetDataColumn(row, stringTable, ref dataTable);
}
else
{
GetDataRow(row, stringTable, ref dataTable);
}
}
return dataTable;
} /// <summary>
/// 根据WorkbookPart获取所有SheetName
/// </summary>
/// <param name="workBookPart"></param>
/// <returns>SheetName集合</returns>
private List<string> GetSheetNames(WorkbookPart workBookPart)
{
List<string> sheetNames = new List<string>();
Sheets sheets = workBookPart.Workbook.Sheets;
foreach (Sheet sheet in sheets)
{
string sheetName = sheet.Name;
if (!string.IsNullOrEmpty(sheetName))
{
sheetNames.Add(sheetName);
}
}
return sheetNames;
} /// <summary>
/// 根据WorkbookPart和sheetName获取该Sheet下所有Row数据
/// </summary>
/// <param name="workBookPart">WorkbookPart对象</param>
/// <param name="sheetName">SheetName</param>
/// <returns>该SheetName下的所有Row数据</returns>
public IEnumerable<Row> GetWorkBookPartRows(WorkbookPart workBookPart, string sheetName)
{
IEnumerable<Row> sheetRows = null;
//根据表名在WorkbookPart中获取Sheet集合
IEnumerable<Sheet> sheets = workBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
if (sheets.Count() == )
{
return null;//没有数据
} WorksheetPart workSheetPart = workBookPart.GetPartById(sheets.First().Id) as WorksheetPart;
//获取Excel中得到的行
sheetRows = workSheetPart.Worksheet.Descendants<Row>();
return sheetRows;
} /// <summary>
/// 根据WorkbookPart和sheetName获取该Sheet下所有Row数据
/// </summary>
/// <param name="workBookPart">WorkbookPart对象</param>
/// <param name="sheetName">SheetName</param>
/// <returns>该SheetName下的所有Row数据</returns>
public IEnumerable<Column> GetWorkBookPartColumns(WorkbookPart workBookPart, string sheetName)
{
IEnumerable<Column> sheetColumns = null;
//根据表名在WorkbookPart中获取Sheet集合
IEnumerable<Sheet> sheets = workBookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName);
if (sheets.Count() == )
{
return null;//没有数据
} WorksheetPart workSheetPart = workBookPart.GetPartById(sheets.First().Id) as WorksheetPart; sheetColumns = workSheetPart.Worksheet.Descendants<Column>(); //获取Excel中得到的行 return sheetColumns;
} /// <summary>
/// 获取Excel中多表的表名
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private List<string> GetExcelSheetNames(string filePath)
{
string sheetName = string.Empty;
List<string> sheetNames = new List<string>();//所有Sheet表名
using (SpreadsheetDocument spreadDocument = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart workBook = spreadDocument.WorkbookPart;
Stream stream = workBook.GetStream(FileMode.Open);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(stream); XmlNamespaceManager xmlNSManager = new XmlNamespaceManager(xmlDocument.NameTable);
xmlNSManager.AddNamespace("default", xmlDocument.DocumentElement.NamespaceURI);
XmlNodeList nodeList = xmlDocument.SelectNodes("//default:sheets/default:sheet", xmlNSManager); foreach (XmlNode node in nodeList)
{
sheetName = node.Attributes["name"].Value;
sheetNames.Add(sheetName);
}
}
return sheetNames;
} #region 采用openxml方式把excel转换成dataTable /// <summary>
/// 构建DataTable的列
/// </summary>
/// <param name="row">OpenXML定义的Row对象</param>
/// <param name="stringTablePart"></param>
/// <param name="dt">须要返回的DataTable对象</param>
/// <returns></returns>
public void GetDataColumn(Row row, SharedStringTable stringTable, ref DataTable dt)
{
DataColumn col = new DataColumn();
Dictionary<string, int> columnCount = new Dictionary<string, int>();
foreach (Cell cell in row)
{
string cellVal = GetValue(cell, stringTable);
col = new DataColumn(cellVal);
if (IsContainsColumn(dt, col.ColumnName))
{
if (!columnCount.ContainsKey(col.ColumnName))
columnCount.Add(col.ColumnName, );
col.ColumnName = col.ColumnName + (columnCount[col.ColumnName]++);
}
dt.Columns.Add(col);
}
}
/// <summary>
/// 构建DataTable的每一行数据,并返回该Datatable
/// </summary>
/// <param name="row">OpenXML的行</param>
/// <param name="stringTablePart"></param>
/// <param name="dt">DataTable</param>
private void GetDataRow(Row row, SharedStringTable stringTable, ref DataTable dt)
{
// 读取算法:按行一一读取单位格,若是整行均是空数据
DataRow dr = dt.NewRow();
int i = ;
int nullRowCount = i;
foreach (Cell cell in row)
{
string cellVal = GetValue(cell, stringTable);
if (cellVal == string.Empty)
{
nullRowCount++;
}
dr[i] = cellVal;
i++;
}
if (nullRowCount != i)
{
dt.Rows.Add(dr);
}
}
/// <summary>
/// 获取单位格的值
/// </summary>
/// <param name="cell"></param>
/// <param name="stringTablePart"></param>
/// <returns></returns>
private string GetValue(Cell cell, SharedStringTable stringTable)
{
//因为Excel的数据存储在SharedStringTable中,须要获取数据在SharedStringTable 中的索引
string value = string.Empty;
try
{
if (cell.ChildElements.Count == )
return value;
value = double.Parse(cell.CellValue.InnerText).ToString();
if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
{
value = stringTable.ChildElements[Int32.Parse(value)].InnerText;
}
}
catch (Exception)
{
value = "N/A";
}
return value;
}
/// <summary>
/// 判断网格是否存在列
/// </summary>
/// <param name="dt">网格</param>
/// <param name="columnName">列名</param>
/// <returns></returns>
public bool IsContainsColumn(DataTable dt, string columnName)
{
if (dt == null || columnName == null)
{
return false;
}
return dt.Columns.Contains(columnName);
} #endregion #region SaveCell
private void InsertTextCellValue(Worksheet worksheet, string column, uint row, string value)
{
Cell cell = ReturnCell(worksheet, column, row);
CellValue v = new CellValue();
v.Text = value;
cell.AppendChild(v);
cell.DataType = new EnumValue<CellValues>(CellValues.String);
worksheet.Save();
}
private void InsertNumberCellValue(Worksheet worksheet, string column, uint row, string value)
{
Cell cell = ReturnCell(worksheet, column, row);
CellValue v = new CellValue();
v.Text = value;
cell.AppendChild(v);
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
worksheet.Save();
}
private static Cell ReturnCell(Worksheet worksheet, string columnName, uint row)
{
Row targetRow = ReturnRow(worksheet, row); if (targetRow == null)
return null; return targetRow.Elements<Cell>().Where(c =>
string.Compare(c.CellReference.Value, columnName + row,
true) == ).First();
}
private static Row ReturnRow(Worksheet worksheet, uint row)
{
return worksheet.GetFirstChild<SheetData>().
Elements<Row>().Where(r => r.RowIndex == row).First();
}
#endregion
}
}

Excel 数据读入到DataSet的更多相关文章

  1. Excel数据导入至Dataset中

    public static DataSet ExcelToDataSet(string ppfilenameurl,string pptable) { string strConn = "P ...

  2. 将excel数据读入matlab

    1.[NUM,TXT,RAW]=xlsread('example'),其中example是你的excel名,假设所有的数据都在example.xls中. 2.NUM返回的是excel中的数据,TXT输 ...

  3. GridView数据导入Excel/Excel数据读入GridView

    原文发布时间为:2008-10-16 -- 来源于本人的百度文章 [由搬家工具导入] 效果图: 解决方案:页面增加一个按钮,单击事件添加如下方法:protected void Button1_Clic ...

  4. 将Excel数据读入DataGridView

    OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Microsoft Excel ...

  5. ASP.NET Excel数据导入数据库

    <identity impersonate="true"/> 是指模拟IIS身份验证 導入錯誤時可刪除 protected void btnImport_Click(o ...

  6. C#将Excel数据导入数据库(MySQL或Sql Server)

    最近一直很忙,很久没写博客了.今天给大家讲解一下如何用C#将Excel数据导入Excel,同时在文章最后附上如何用sqlserver和mysql工具导入数据. 导入过程大致分为两步: 1.将excel ...

  7. 使用OpenXml把Excel中的数据导出到DataSet中

    public class OpenXmlHelper { /// <summary> /// 读取Excel数据到DataSet中,默认读取所有Sheet中的数据 /// </sum ...

  8. C# 将Excel里面的数据填充到DataSet中

    /// <summary> /// 将Excel表里的数据填充到DataSet中 /// </summary> /// <param name="filenam ...

  9. asp.net实现 EXCEL数据导入到数据库功能

    在项目中经常要用EXCEL导入数据到数据库,提高工作效率. 注意:EXCEL中的第一行不能导入. 下面是源码: IntoExcel.aspx: [csharp] <%@ Page Languag ...

随机推荐

  1. Axure RP 8 下载 激活可以使用的授权码、用户名、秘钥等

    百度云下载地址: 链接:https://pan.baidu.com/s/13z0IPsKbLdPktiCD5eUe-A 提取码: oxhw 用户名: axureuser 序列号: 8wFfIX7a8h ...

  2. Ruby 基础教程 第二部分 Ruby 的基础 第4章

    第二部分 Ruby 的基础 第4章~第6章 这一部分是 Ruby 编程需要遵守的规则. 第四章 对象,变量与常量 对象 & 类 对象的常见种类: 数值对象 字符串对象 数组.散列对象 正则表达 ...

  3. springboot---->错误: 找不到或无法加载主类

    刚开始是往上面箭头指出的方向去找问题的原因,但是试了各种方法后问题还是没有解决,于是乎我把焦点转去查看eclipsede控制台处: 主要的错误提示如下: Archive for required li ...

  4. Shell函数和数组

    函数的返回值用return,脚本的返回值用exit shell函数只允许返回数字,若不是则报line 6: return: num: numeric argument required:若是写了ret ...

  5. Linux文件系统管理

    第九讲 文件系统管理   基础知识点:   硬盘的构成:主要由盘片.机械手臂.磁头与主轴马达所组成,实际的数据都是写在具有磁性物质上的盘片,通过主轴马达让盘片转动,机械手臂可伸展让磁头在盘片上读取数据 ...

  6. 浅谈mysql

    关于数据库其实我们可以简单的理解为存储货物的一个厂库,里面分别是按照一定的分类存放的物品,然后人们有时会从厂库中拿走或存储一些物品,有时也会更改或增加一些分类 这些物品都分门别类的存放在厂库中,方便人 ...

  7. leetcode-algorithms-26 Remove Duplicates from Sorted Array

    leetcode-algorithms-26 Remove Duplicates from Sorted Array Given a sorted array nums, remove the dup ...

  8. MRBS开源会议室预订系统安装

    MRBS系统官方网址  https://mrbs.sourceforge.io/ 最近在找一份开源的会议室预订系统,找了很多种,ASP,PHP的,测试发现MRBS无疑是最好的.开源社区对其介绍如下:M ...

  9. ThinkPHP3上传文件中遇到的问题

    在用ThinkPHP3上传图片的开发过程中遇到如下几个问题: 上传根目录不存在!请尝试手动创建:./Uploads/: 上传的图片,中文名称乱码: 上传文件时会自动生成一个以当前日期命名的文件夹,并将 ...

  10. [CodeForces - 447C] C - DZY Loves Sequences

    C - DZY Loves Sequences DZY has a sequence a, consisting of n integers. We'll call a sequence ai, ai ...