原文出处: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;
}
}

最新文章

  1. 信号量 semaphore 和 @synchronized 的运用
  2. 通过代理连接go01ge
  3. Linux WAS7 启动异常
  4. [快速数论变换 NTT]
  5. mongoDB 入门指南、示例
  6. 使用 Spring 2.5 基于注解驱动的 Spring MVC--转
  7. 4. 绘制光谱曲线QGraphicsView类
  8. SQL Server 查看表定义的 2 种方法
  9. apache添加fastcgi支持
  10. 实现一个javascript手势库 -- base-gesture.js
  11. JAVAOO零碎--内存叠加
  12. Python循环列表删除元素问题
  13. SQL中什么时候需要使用游标?使用游标的步骤
  14. Missing artifact javax.transaction:jta:jar:1.0.1B
  15. day48
  16. MyBatis中对于字符串blank(null、empty)的判定方法
  17. BP神经网络的Java实现(转)
  18. 了解python wed 框架
  19. HDU 2087 剪花布条(字符串匹配,KMP)
  20. 微信小程序 - 反编译线上源码

热门文章

  1. 2019年3月10日 装饰器进阶-模拟session
  2. writeup
  3. centos设置网卡开机自启动
  4. Navicat Premium 12
  5. Elasticsearch .net client NEST使用说明 2.x -更新版
  6. CocoaPods 中删除不需要的第三方
  7. vue 学习笔记(二)
  8. Redis(一)--安装与简介
  9. label 的for属性总结
  10. vue2 作用域插槽slot-scope详解