How to convert Word table into Excel using OpenXML
原文出处:https://code.msdn.microsoft.com/How-to-convert-Word-table-0cb4c9c3
class Program
{
static void Main(string[] args)
{
string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string wordFile = appPath + "\\TestDoc.docx"; DataTable dataTable = ReadWordTable(wordFile); if (dataTable != null)
{
string sFile = appPath + "\\ExportExcel.xlsx"; ExportDataTableToExcel(dataTable, sFile); Console.WriteLine("Contents of word table exported to excel spreadsheet"); Console.ReadKey();
}
} /// <summary>
/// This method reads the contents of table using openxml sdk
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static DataTable ReadWordTable(string fileName)
{
DataTable table; try
{
using (var document = WordprocessingDocument.Open(fileName, false))
{
var docPart = document.MainDocumentPart;
var doc = docPart.Document; DocumentFormat.OpenXml.Wordprocessing.Table myTable = doc.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Table>().First(); List<List<string>> totalRows = new List<List<string>>();
int maxCol = ; foreach (TableRow row in myTable.Elements<TableRow>())
{
List<string> tempRowValues = new List<string>();
foreach (TableCell cell in row.Elements<TableCell>())
{
tempRowValues.Add(cell.InnerText);
} maxCol = ProcessList(tempRowValues, totalRows, maxCol);
} table = ConvertListListStringToDataTable(totalRows, maxCol);
} return table;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); return null;
}
} /// <summary>
/// Add each row to the totalRows.
/// </summary>
/// <param name="tempRows"></param>
/// <param name="totalRows"></param>
/// <param name="MaxCol">the max column number in rows of the totalRows</param>
/// <returns></returns>
private static int ProcessList(List<string> tempRows, List<List<string>> totalRows, int MaxCol)
{
if (tempRows.Count > MaxCol)
{
MaxCol = tempRows.Count;
} totalRows.Add(tempRows);
return MaxCol;
} /// <summary>
/// This method converts list data to a data table
/// </summary>
/// <param name="totalRows"></param>
/// <param name="maxCol"></param>
/// <returns>returns datatable object</returns>
private static DataTable ConvertListListStringToDataTable(List<List<string>> totalRows, int maxCol)
{
DataTable table = new DataTable();
for (int i = ; i < maxCol; i++)
{
table.Columns.Add();
}
foreach (List<string> row in totalRows)
{
while (row.Count < maxCol)
{
row.Add("");
}
table.Rows.Add(row.ToArray());
}
return table;
} /// <summary>
/// This method exports datatable to a excel file
/// </summary>
/// <param name="table">DataTable</param>
/// <param name="exportFile">Excel file name</param>
private static void ExportDataTableToExcel(DataTable table, string exportFile)
{
try
{
// Create a spreadsheet document by supplying the filepath.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(exportFile, SpreadsheetDocumentType.Workbook); // Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook(); // Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData()); // Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets()); // Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = ,
Name = "mySheet"
};
sheets.Append(sheet); SheetData data = worksheetPart.Worksheet.GetFirstChild<SheetData>(); //add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32); foreach (DataColumn column in table.Columns)
{
Cell headerCell = createTextCell(
table.Columns.IndexOf(column) + ,
,
column.ColumnName); header.AppendChild(headerCell);
}
data.AppendChild(header); //loop through each data row
DataRow contentRow;
for (int i = ; i < table.Rows.Count; i++)
{
contentRow = table.Rows[i];
data.AppendChild(createContentRow(contentRow, i + ));
} workbookpart.Workbook.Save(); // Close the document.
spreadsheetDocument.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// This method creates text cell
/// </summary>
/// <param name="columnIndex"></param>
/// <param name="rowIndex"></param>
/// <param name="cellValue"></param>
/// <returns></returns>
private static Cell createTextCell( int columnIndex, int rowIndex, object cellValue)
{
Cell cell = new Cell(); cell.DataType = CellValues.InlineString;
cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString();
DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); t.Text = cellValue.ToString();
inlineString.AppendChild(t);
cell.AppendChild(inlineString); return cell;
} /// <summary>
/// This method creates content row
/// </summary>
/// <param name="dataRow"></param>
/// <param name="rowIndex"></param>
/// <returns></returns>
private static Row createContentRow( DataRow dataRow, int rowIndex)
{
Row row = new Row
{
RowIndex = (UInt32)rowIndex
}; for (int i = ; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + , rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
} /// <summary>
/// Formates or gets column name
/// </summary>
/// <param name="columnIndex"></param>
/// <returns></returns>
private static string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier; while (dividend > )
{
modifier = (dividend - ) % ;
columnName =
Convert.ToChar( + modifier).ToString() + columnName;
dividend = (int)((dividend - modifier) / );
} return columnName;
}
}
How to convert Word table into Excel using OpenXML的更多相关文章
- 导出网页中的table到excel
导出网页中的table到excel的两种简便方法: 1. 纯 JavaScript 方法,缺点只支持IE浏览器 var elTable = document.getElementById(" ...
- Word, PPT和Excel的常用技巧(持续更新)
本文的目的是记录平时使用Word, PowerPoint和Excel的过程中的一些小技巧,用于提升工作效率. 此文会不定期的更新,更新频率完全取决于实际使用遇到的问题的次数. 目录 Word Powe ...
- 使用C#动态生成Word文档/Excel文档的程序测试通过后,部署到IIS服务器上,不能正常使用的问题解决方案
使用C#动态生成Word文档/Excel文档的程序功能调试.测试通过后,部署到服务器上,不能正常使用的问题解决方案: 原因: 可能asp.net程序或iis访问excel组件时权限不够(Ps:Syst ...
- <转>HTML中的table转为excel
转换html 中的table 为excel,firefox浏览器支持,代码如下 <%@ page language="java" contentType="text ...
- 支持IE,FireFox,Chrome三大主流浏览器,通过js+Flash方式将table导出Excel文件
今天在做项目的时候,遇到了前端下载Excel的功能,结果原先的代码,如下: function generate_excel(tableid) { var table = document ...
- Html table 实现Excel多格粘贴
Html table 实现Excel多格粘贴 电商网站的后台总少不了各种繁杂数据的录入,旁边的运营妹子录完第138条商品的时候,终于忍不住转身吼到:为什么后台的录入表不能像Excel那样多行粘贴!!! ...
- js实现table导出Excel,保留table样式
浏览器环境:谷歌浏览器 1.在导出Excel的时候,保存table的样式,有2种方法,①是在table的行内写style样式,②是在模板里面添加样式 2.第一种方式:行内添加样式 <td sty ...
- html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式
先上代码 <script type="text/javascript" language="javascript"> var idTmr; ...
- ASP如何将table导出EXCEL表格
网页导出excel表格非常常用,对于一些加载<table>的数据网页,经常会用到这种功能,下面和大家分享一下ASP如何导出EXCEL表格 工具/原料 ASP编辑器 方法/步骤 ...
随机推荐
- js中call()的用法
A.call(B,x,y) 1`改变函数A的this指向,使之指向B; 2` 把A函数放到B中运行,x和y是A函数的参数. //父类 Person function Person() { ...
- vue filters中使用data中数据
vue filters中 this指向的不是vue实例,但想要获取vue实例中data中的数据,可以采用下面方法.在 beforeCreate中将vue实例赋值给全局变量app0,然后filters中 ...
- [opengl]Clion配置opengl
如何在Clion中编写Opengl程序 首先下载 GLAD GLFW 创建Clion工程 在工程中创建文件夹lib.dll.include文件夹 把下载下来的东西放入对应的文件夹 CMakeLists ...
- Python中常见的正则表达式符号
? 匹配零次或一次前面的分组 * 匹配零次或多次前面的分组 + 匹配一次或多次前面的分组 {n} 匹配n次前面的分组 {n,} 匹配n次或更多次前面的分组 {,m} 匹配零次到m次前面的分组 ...
- Hash索引和BTree索引区别【转】
索引是帮助mysql获取数据的数据结构.最常见的索引是Btree索引和Hash索引. 不同的引擎对于索引有不同的支持:Innodb和MyISAM默认的索引是Btree索引:而Mermory默认的索引是 ...
- VMware虚拟机安装CentOS 6.9图文教程
1.Win7安装VMware虚拟机比较简单,直接从官网下载VMware安装即可,这里不再叙述. 2.接着从CentOS官网直接下载CentOS 6.9的iso镜像文件. 3.打开VMware,点击创建 ...
- bean 装配
1.装配方式 (1)在xml进行显式装配 (2)在java中进行显式装配 (3)隐式的bean发现机制和自动装配 2.装配方式(3)实现 (1)创建bean /** * @component告诉spr ...
- gcc使用及动静态库制作
一. GCC的使用 1. GCC的编译过程 (1)预处理(cpp)gcc -E(输出问价通常以 .i 结尾),将头文件展开,宏替换等操作: (2)编译器(gcc)gcc -S(输出问价以 .s 结尾) ...
- JSR107缓存规范
Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry. CachingProvider定义了创建. ...
- diango admin 添加成员报错
[报错内容]: IntegrityError at /admin/users/userprofile/add/ (1452, 'Cannot add or update a child row: a ...