/// <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写的帮助类的更多相关文章

  1. Open-Xml SDK使用介绍

    Office Open XML 简称为 ooxml ,是Microsoft 在 Office 2007 之后推行的标准格式,用在 Excel, Word, PPT 等文件.已确定为国际标准. Open ...

  2. OpenXml SDK学习笔记(1):Word的基本结构

    能写多少篇我就不确定了,可能就这一篇就太监了,也有可能会写不少. OpenXml SDK 相信很多人都不陌生,这个就是管Office一家的文档格式,Word, Excel, PowerPoint等都用 ...

  3. OpenXml Sdk 根据Word模板导出到word

    一:OpenXml Sdk 简介 Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档.演示文稿和电子表格的国际化开放标准,可免费供多个应用 ...

  4. js 一个自写的 监测类

    自从认识了jQuery后,很多页面加载入口,都放在document.ready里面.但是有时候这个觉得ready加载太慢, 这个[监测类 ]就开始产生了 效果类似这个. 每10毫秒检查一次,直到加载了 ...

  5. Java基础-继承-编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。

    #29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight.小车类Car是Vehicle的子类,其中包含的属性有载人数 loader.卡车类T ...

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

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

  7. [Office][C#] NPOI、OpenXML SDK、OpenOffice.org SDK 写入资料到 EXCEL 档案[转]

    原文地址:http://www.dotblogs.com.tw/chou/archive/2010/04/29/14912.aspx 一.簡介 要將資料寫入 EXCEL 檔案有許多的方法,但假如電腦不 ...

  8. ItcastOA_设计BaseDao_设计DAO接口和实现类_写DAO实现类中的方法内容

    3. 基础功能 3.1. 设计BaseDao接口与BaseDaoImpl类 每个实体都应有一个对应的Dao,他封装了对这个实体的数据库操作.例 实体Dao接口实现类 ================= ...

  9. 基于七牛Python SDK写的一个批量下载脚本

    前言 上一篇基于七牛Python SDK写的一个同步脚本所写的脚本只支持上传,不支持文件下载. 虽然这个需求不太强烈,但有可能有人(在备份.迁移时)需要,而官方有没提供对应的工具,所以我就把这个功能也 ...

随机推荐

  1. C# 自定义异常的方法源码演示及说明

    内容之余,把做工程过程中较好的内容段备份一下,下边内容是关于C# 自定义异常的方法演示及说明的内容,希望能对各位朋友有一些好处. using System;using System.Collectio ...

  2. kubernetes学习笔记之七: Ingress-nginx 部署使用

    一.Ingress 简介 在Kubernetes中,服务和Pod的IP地址仅可以在集群网络内部使用,对于集群外的应用是不可见的.为了使外部的应用能够访问集群内的服务,在Kubernetes 目前 提供 ...

  3. orcal 安装失败解决办法

    若安装失败

  4. orcal 程序自动和手动项

    orcal在电脑开机后,为了可以使用 这两个服务设置为自动(为了使用),其他设置为手动(减少电脑压力):

  5. Eclipse 中Git的使用及如何解决冲突

    1. 如何导入已有Git项目 1.1 File——>import… 出现以下界面 1.2 找到Git,然后双击‘Project from Git.或者点击next 1.3 双击Clone URI ...

  6. STL里的内存池实现

    这个貌似有点复杂,解决的主要问题 就是 减少 内存分配次数,减少用户态核心态切换中断次数,提高运行速度,预分配 和线程池一个道理,预分配 ////////////////////自由链表 union ...

  7. Sql Server数据库之identity(自增)

    一.identity的基本用法 1.identity的含义: identity表示该字段的值会自动更新,通常情况下,不允许直接修改identity修饰的字段,否则编译会报错 2.基本语法 列名  数据 ...

  8. gitlab 502

    经过一个下午的查找终于发现了错误,原来是在服务器上还开启了一个tomcat服务,占用了8080端口,使GitLab的unicorn服务不能开启. 最后在/etc/gitlab/gitlab.rb 中做 ...

  9. 业务数据实体(model) 需要克隆的方法

    业务数据实体(model) 需要克隆的时候 可以使用 Json.Deserialize<InquireResult>(Json.Serialize<InquireResult> ...

  10. TPL DataFlow初探(二)

    上一篇简单的介绍了TDF提供的一些Block,通过对这些Block配置和组合,可以满足很多的数据处理的场景.这一篇将继续介绍与这些Block配置的相关类,和挖掘一些高级功能. 在一些Block的构造函 ...