其于OpenXml SDK写的帮助类
/// <summary>
/// 其于OpenXml SDK写的帮助类
/// </summary>
public static class OpenXmlHelper
{
/// <summary>
/// 单元格样式
/// </summary>
public static uint CellStyleIndex { get; set; } /// <summary>
/// 删除sheet
/// </summary>
/// <param name="fileName"></param>
/// <param name="sheetToDelete"></param>
/// <returns></returns>
public static bool XLDeleteSheet(string fileName, string sheetToDelete)
{
bool returnValue = false;
using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, true))
{
XmlDocument doc = new XmlDocument();
doc.Load(xlDoc.WorkbookPart.GetStream()); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
nsManager.AddNamespace("d", doc.DocumentElement.NamespaceURI); string searchString = string.Format("//d:sheet[@name='{0}']", sheetToDelete);
XmlNode node = doc.SelectSingleNode(searchString, nsManager);
if (node != null)
{
XmlAttribute relationAttribute = node.Attributes["r:id"];
if (relationAttribute != null)
{
string relId = relationAttribute.Value;
xlDoc.WorkbookPart.DeletePart(relId);
node.ParentNode.RemoveChild(node);
doc.Save(xlDoc.WorkbookPart.GetStream(FileMode.Create));
returnValue = true;
}
}
}
return returnValue;
} /// <summary>
/// 获取Worksheet
/// </summary>
/// <param name="document">document对象</param>
/// <param name="sheetName">sheetName可空</param>
/// <returns>Worksheet对象</returns>
public static Worksheet GetWorksheet(this SpreadsheetDocument document, string sheetName = null)
{
var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
var sheet = (sheetName == null
? sheets.FirstOrDefault()
: sheets.FirstOrDefault(s => s.Name == sheetName)) ?? sheets.FirstOrDefault(); var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
return worksheetPart.Worksheet;
}
/// <summary>
/// 获取第一个SheetData
/// </summary>
/// <param name="document">SpreadsheetDocument对象</param>
/// <param name="sheetName">sheetName可为空</param>
/// <returns>SheetData对象</returns>
public static SheetData GetFirstSheetData(this SpreadsheetDocument document, string sheetName = null)
{
return document.GetWorksheet(sheetName).GetFirstChild<SheetData>();
} /// <summary>
/// 获取第一个SheetData
/// </summary>
/// <param name="worksheet">Worksheet对象</param>
/// <returns>SheetData对象</returns>
public static SheetData GetFirstSheetData(this Worksheet worksheet)
{
return worksheet.GetFirstChild<SheetData>();
} /// <summary>
/// 获了共享字符的表格对象
/// </summary>
/// <param name="document">SpreadsheetDocument</param>
/// <returns>SharedStringTablePart对角</returns>
public static SharedStringTablePart GetSharedStringTable(this SpreadsheetDocument document)
{
var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
return sharedStringTable;
} /// <summary>
/// 修改单元格的内容.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
public static void UpdateCellText(this SheetData sheetData, string cellName, string cellText)
{
var cell = sheetData.GetCell(cellName);
if (cell == null)
{
return;
}
cell.UpdateCellText(cellText);
} /// <summary>
/// 设置单元格的值.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
public static void SetCellValue(this SheetData sheetData, string cellName, object cellText = null)
{
SetCellValue(sheetData, cellName, cellText ?? string.Empty, CellStyleIndex);
} /// <summary>
/// 添加一个单元格
/// </summary>
/// <param name="row">Row对象</param>
/// <param name="cellName">单元格名称</param>
/// <param name="cellText">单元格文本</param>
/// <param name="cellStyleIndex">样式</param>
private static void CreateCell(this Row row, string cellName, object cellText, uint cellStyleIndex)
{
var refCell =
row.Elements<Cell>()
.FirstOrDefault(
cell =>
string.Compare(cell.CellReference.Value, cellName, StringComparison.OrdinalIgnoreCase) > );
var resultCell = new Cell { CellReference = cellName };
resultCell.UpdateCell(cellText, cellStyleIndex);
row.InsertBefore(resultCell, refCell);
}
/// <summary>
/// 设置单元格的值.
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <param name="cellStyleIndex">
/// The cell style index.
/// </param>
private static void SetCellValue(this SheetData sheetData, string cellName, object cellText, uint cellStyleIndex)
{
uint rowIndex = GetRowIndex(cellName);
var row = sheetData.GetRow(rowIndex);
if (row == null)
{
row = new Row { RowIndex = rowIndex };
row.CreateCell(cellName, cellText, cellStyleIndex);
sheetData.Append(row);
}
else
{
var cell = row.GetCell(cellName);
if (cell == null)
{
row.CreateCell(cellName, cellText, cellStyleIndex);
}
else
{
cell.UpdateCell(cellText, cellStyleIndex);
}
}
} /// <summary>
/// The get rows count.
/// </summary>
/// <param name="rows">
/// The rows.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public static int GetRowsCount(this IEnumerable<Row> rows)
{
return rows.GroupBy(x => x.RowIndex.Value).Count();
} /// <summary>
/// 根据行索引获取单元
/// </summary>
/// <param name="rows">
/// The rows.
/// </param>
/// <param name="rowIndex">
/// The row index.
/// </param>
/// <returns>
/// Cell集合
/// </returns>
public static IList<Cell> GetCells(this IEnumerable<Row> rows, int rowIndex)
{
return rows.Where(row => row.RowIndex.Value == rowIndex).SelectMany(row => row.Elements<Cell>()).ToList();
} /// <summary>
/// 获取单元格值
/// </summary>
/// <param name="cells">
/// The cells.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <param name="stringTablePart">
/// The string table part.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string GetCellValue(this IEnumerable<Cell> cells, string cellName, SharedStringTablePart stringTablePart)
{
if (cells == null)
{
throw new ArgumentNullException("cells");
}
if (cellName == null)
{
throw new ArgumentNullException("cellName");
}
var cell = (from item in cells where item.CellReference == cellName select item).FirstOrDefault();
if (cell == null)
{
return string.Empty;
}
if (cell.ChildElements.Count == )
{
return string.Empty;
}
var value = cell.CellValue.InnerText;
if (cell.DataType == null)
{
return value;
}
switch (cell.DataType.Value)
{
case CellValues.SharedString:
if (stringTablePart != null)
{
value = stringTablePart.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
value = value == "" ? "FALSE" : "TRUE";
break;
}
return value;
} /// <summary>
/// 验证文档
/// </summary>
/// <param name="document">
/// The document.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string ValidateDocument(this SpreadsheetDocument document)
{
var msg = new StringBuilder();
try
{
var validator = new OpenXmlValidator();
int count = ;
foreach (ValidationErrorInfo error in validator.Validate(document))
{
count++;
msg.Append("\nError " + count)
.Append("\nDescription: " + error.Description)
.Append("\nErrorType: " + error.ErrorType)
.Append("\nNode: " + error.Node)
.Append("\nPath: " + error.Path.XPath)
.Append("\nPart: " + error.Part.Uri)
.Append("\n-------------------------------------------");
}
}
catch (Exception ex)
{
msg.Append(ex.Message);
} return msg.ToString();
} /// <summary>
/// 根据单元格名称获取行索引.
/// </summary>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="uint"/>.
/// </returns>
private static uint GetRowIndex(string cellName)
{
var regex = new Regex(@"\d+");
var match = regex.Match(cellName);
return uint.Parse(match.Value);
} /// <summary>
/// The get cell data type.
/// </summary>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <returns>
/// The <see cref="CellValues"/>.
/// </returns>
private static CellValues GetCellDataType(object cellText)
{
var type = cellText.GetType();
switch (type.Name)
{
case "Int32":
case "Decimal":
case "Double":
case "Int64":
return CellValues.Number;
case "String":
return CellValues.String;
//// case "DateTime":
//// return CellValues.Date;
default:
return CellValues.String;
}
} /// <summary>
/// 修改单元格内容(文本、样式)
/// </summary>
/// <param name="cell">
/// The cell.
/// </param>
/// <param name="cellText">
/// The cell text.
/// </param>
/// <param name="cellStyleIndex">
/// The cell style index.
/// </param>
private static void UpdateCell(this Cell cell, object cellText, uint cellStyleIndex)
{
cell.UpdateCellText(cellText);
cell.StyleIndex = cellStyleIndex;
} /// <summary>
/// 修改单元格的文本
/// </summary>
/// <param name="cell">Cell对象</param>
/// <param name="cellText">文本字符串</param>
private static void UpdateCellText(this Cell cell, object cellText)
{
cell.DataType = GetCellDataType(cellText);
cell.CellValue = cell.CellValue ?? new CellValue();
cell.CellValue.Text = cellText.ToString();
} /// <summary>
/// 获取行
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="rowIndex">
/// The row index.
/// </param>
/// <returns>
/// The <see cref="Row"/>.
/// </returns>
private static Row GetRow(this SheetData sheetData, long rowIndex)
{
return sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
} /// <summary>
/// 获取单元格
/// </summary>
/// <param name="row">
/// The row.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="Cell"/>.
/// </returns>
private static Cell GetCell(this Row row, string cellName)
{
return row.Elements<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
} /// <summary>
/// 获取单元格
/// </summary>
/// <param name="sheetData">
/// The sheet data.
/// </param>
/// <param name="cellName">
/// The cell name.
/// </param>
/// <returns>
/// The <see cref="Cell"/>.
/// </returns>
private static Cell GetCell(this SheetData sheetData, string cellName)
{
return sheetData.Descendants<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
}
#region 样式 /*
public static Borders CreateStylesheet()
{
//Stylesheet stylesheet1 = new Stylesheet()
// {
// MCAttributes =
// new MarkupCompatibilityAttributes()
// {
// Ignorable = "x14ac"
// }
// };
//stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
//stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); var borders1 = new Borders(
new Border(
// Index 1 - Applies a Left, Right, Top, Bottom border to a cell
new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new DiagonalBorder())); // stylesheet1.Append(borders1);
// return stylesheet1;
return borders1;
} public static Border CreateBorder()
{
//Stylesheet stylesheet1 = new Stylesheet()
// {
// MCAttributes =
// new MarkupCompatibilityAttributes()
// {
// Ignorable = "x14ac"
// }
// };
//stylesheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
//stylesheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); // var borders1 = new Borders(
return new Border(
// Index 1 - Applies a Left, Right, Top, Bottom border to a cell
new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
new DiagonalBorder()); // stylesheet1.Append(borders1);
// return stylesheet1;
// return borders1;
} */
#endregion
}
其于OpenXml SDK写的帮助类的更多相关文章
- Open-Xml SDK使用介绍
Office Open XML 简称为 ooxml ,是Microsoft 在 Office 2007 之后推行的标准格式,用在 Excel, Word, PPT 等文件.已确定为国际标准. Open ...
- OpenXml SDK学习笔记(1):Word的基本结构
能写多少篇我就不确定了,可能就这一篇就太监了,也有可能会写不少. OpenXml SDK 相信很多人都不陌生,这个就是管Office一家的文档格式,Word, Excel, PowerPoint等都用 ...
- OpenXml Sdk 根据Word模板导出到word
一:OpenXml Sdk 简介 Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档.演示文稿和电子表格的国际化开放标准,可免费供多个应用 ...
- js 一个自写的 监测类
自从认识了jQuery后,很多页面加载入口,都放在document.ready里面.但是有时候这个觉得ready加载太慢, 这个[监测类 ]就开始产生了 效果类似这个. 每10毫秒检查一次,直到加载了 ...
- Java基础-继承-编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。
#29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight.小车类Car是Vehicle的子类,其中包含的属性有载人数 loader.卡车类T ...
- csharp:using OpenXml SDK 2.0 and ClosedXML read excel file
https://openxmlexporttoexcel.codeplex.com/ http://referencesource.microsoft.com/ 引用: using System; u ...
- [Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 写入资料到 EXCEL 档案[转]
原文地址:http://www.dotblogs.com.tw/chou/archive/2010/04/29/14912.aspx 一.簡介 要將資料寫入 EXCEL 檔案有許多的方法,但假如電腦不 ...
- ItcastOA_设计BaseDao_设计DAO接口和实现类_写DAO实现类中的方法内容
3. 基础功能 3.1. 设计BaseDao接口与BaseDaoImpl类 每个实体都应有一个对应的Dao,他封装了对这个实体的数据库操作.例 实体Dao接口实现类 ================= ...
- 基于七牛Python SDK写的一个批量下载脚本
前言 上一篇基于七牛Python SDK写的一个同步脚本所写的脚本只支持上传,不支持文件下载. 虽然这个需求不太强烈,但有可能有人(在备份.迁移时)需要,而官方有没提供对应的工具,所以我就把这个功能也 ...
随机推荐
- linux vue项目+npm run build + nginx
系统 环境 vue nginx 步骤 1.打包vue项目 2.配置nginx 打包vue项目 1.项目配置 我们使用服务器的8000端口 2.打包 # npm run build 打包成功会创 ...
- JOSN转列格式(csv文件)
推荐网站 https://json-csv.com/ 限制1M大小
- [java,2017-05-16] java中清空StringBuffer的方法以及耗费时间比较
java中清空StringBuffer的方法,我能想到的有4种: 1. buffer.setLength(0); 设置长度为0 2. buffer.delete(0, buffer.length() ...
- 三. html&JavaScript&ajax 部 分
1. 判 断 第 二 个 日 期 比 第 一 个 日 期 大 如何用脚本判断用户输入的的字符串是下面的时间格式2004-11-21必须要保证用户 的输入是此格式,并且是时间,比如说月份不大于12等等, ...
- django 开发之前后端分离开发模式
1. 什么是前后端分离开发的概念: 前端页面运行前端服务器上,负责页面的渲染(静态文件的加载)与跳转 后端代码运行在后端服务器上, 负责数据的处理(提供数据请求的接口) 2. 前后端分离开发碰到的问题 ...
- HTML5-网页添加视频-菜鸟笔记
一.标签 <video> 在html5中,有这么个标签 <video> 标签. <video> 允许你简单的嵌入一段视频. 二.浏览器的兼容性问题 WebM 容器通 ...
- JavaScript: For , For/in , For/of
For: define: The for statement can customize how many times you want to execute code Grammar: for (c ...
- STL里的内存池实现
这个貌似有点复杂,解决的主要问题 就是 减少 内存分配次数,减少用户态核心态切换中断次数,提高运行速度,预分配 和线程池一个道理,预分配 ////////////////////自由链表 union ...
- 26.Hibernate-主键和映射.md
目录 1.复合主键映射 [toc] 2.集合映射 2.1Set集合 2.2其他集合 [toc] 3.集合数据的读取 [toc] 4.一对多和多对一映射 4.1概念 4.2配置和开发 4.2.1关键点 ...
- Ubuntu下解决MySQL自启动,chkconfig list 全部off 情况
chkconfig命令是用于RedHat/Fedora发行版的,而对于像Ubuntu之类的Debian发行版,应该使用这个命令: sudo update-rc.d mysql defaults 验证一 ...