Word表格到Excel [英] Word table to Excel
本文介绍了Word表格到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以使用开放式XML
解决方案
来复制Excel电子表格中的单词表,包括格式,你好
gc70,
请尝试参考下面的例子。
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("导出到excel电子表格的单词表的内容);
Console.ReadKey();
}
}
///< summary>
///此方法使用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< string>> totalRows = new List< List< string>>();
int maxCol = 0;
foreach(myTable.Elements中的TableRow行< TableRow>())
{
List< string> tempRowValues = new List< string>();
foreach(TableCell单元格在row.Elements< TableCell>())
{
tempRowValues.Add(cell.InnerText);
}
maxCol = ProcessList(tempRowValues,totalRows,maxCol);
}
table = ConvertListListStringToDataTable(totalRows,maxCol);
}
返回表;
}
catch(exception ex)
{
Console.WriteLine(ex.Message);
返回null;
}
}
///< summary>
///将每一行添加到totalRows。
///< / summary>
///< param name =" tempRows">< / param>
///< param name =" totalRows">< / param>
///< param name =" MaxCol"> 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);
返回MaxCol;
}
///< summary>
///此方法将列表数据转换为数据表
///< / summary>
///< param name =" totalRows">< / param>
///< param name =" maxCol">< / param>
///< returns>返回数据表对象< / returns>
private static DataTable ConvertListListStringToDataTable(List< List< string>> totalRows,int maxCol)
{
DataTable table = new DataTable();
for(int i = 0; i< maxCol; i ++)
{
table.Columns.Add();
}
foreach(list< string> totalRows中的行)
{
while(row.Count< maxCol)
{
row.Add( "");
}
table.Rows.Add(row.ToArray());
}
返回表;
}
///< summary>
///此方法将数据表导出到excel文件
///< / summary>
///< param name =" table"> DataTable< / param>
///< param name =" exportFile"> Excel文件名< / param>
private static void ExportDataTableToExcel(DataTable table,string exportFile)
{
try
{
//通过提供文件路径创建电子表格文档。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument。
Create(exportFile,SpreadsheetDocumentType.Workbook);
//在文档中添加WorkbookPart。
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
//将WorkheetPart添加到WorkbookPart。
WorksheetPart worksheetPart = workbookpart.AddNewPart< WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
//将工作表添加到工作簿。
表格表格= spreadsheetDocument.WorkbookPart.Workbook。
AppendChild< Sheets>(new Sheets());
//附加新工作表并将其与工作簿关联。
工作表=新工作表()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name =" mySheet"
};
sheets.Append(sheet);
SheetData data = worksheetPart.Worksheet.GetFirstChild< SheetData>();
//将列名添加到第一行
Row header = new Row();
header.RowIndex =(UInt32)1;
foreach(table.Columns中的DataColumn列)
{
Cell headerCell = createTextCell(
table.Columns.IndexOf(column)+ 1,
1,
column.ColumnName);
header.AppendChild(headerCell);
}
data.AppendChild(header);
//遍历每个数据行
DataRow contentRow;
for(int i = 0; i< table.Rows.Count; i ++)
{
contentRow = table.Rows [i];
data.AppendChild(createContentRow(contentRow,i + 2));
}
workbookpart.Workbook.Save();
//关闭文件。
spreadsheetDocument.Close();
}
catch(exception ex)
{
Console.WriteLine(ex.Message);
}
}
///< summary>
///此方法创建文本单元
///< / 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);
返回单元格;
}
///< summary>
///此方法创建内容行
///< / 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 = 0; i< dataRow.Table.Columns.Count; i ++)
{
Cell dataCell = createTextCell(i + 1,rowIndex,dataRow [一世]);
row.AppendChild(dataCell);
}
返回行;
}
///< summary>
/// Formates或获取列名
///< / summary>
///< param name =" columnIndex">< / param>
///< returns>< / returns>
私有静态字符串getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier;
while(dividend> 0)
{
modifier =(dividend - 1)%26;
columnName =
Convert.ToChar(65 + modifier).ToString()+ columnName;
dividend =(int)((dividend - modifier)/ 26);
}
return columnName;
}
}参考:
问候
It is possible to copy a word table in an Excel spreadsheet, including the formats, using open XML
解决方案
Hi gc70,
Please try to refer example below.
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 = 0; 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 = 0; 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 = 1, 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)1; foreach (DataColumn column in table.Columns) { Cell headerCell = createTextCell( table.Columns.IndexOf(column) + 1, 1, column.ColumnName); header.AppendChild(headerCell); } data.AppendChild(header); //loop through each data row DataRow contentRow; for (int i = 0; i < table.Rows.Count; i++) { contentRow = table.Rows[i]; data.AppendChild(createContentRow(contentRow, i + 2)); } 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 = 0; i < dataRow.Table.Columns.Count; i++) { Cell dataCell = createTextCell(i + 1, 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 > 0) { modifier = (dividend - 1) % 26; columnName = Convert.ToChar(65 + modifier).ToString() + columnName; dividend = (int)((dividend - modifier) / 26); } return columnName; } }Reference:
How to convert Word table into Excel using OpenXML
Regards
这篇关于Word表格到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文