我在Word中有以下测试表,其中一个单元格具有多级列表:
使用下面的代码,我可以将Word表中的单元格复制到Excel工作表中的相应单元格:
foreach (Microsoft.Office.Interop.Word.Table table in objDoc.Tables)
{
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 1; col <= table.Columns.Count; col++)
{
string text = table.Cell(row, col).Range.Text;
worksheet.Cells[row, col] = text;
}
}
}
但是,我得到以下结果,其中包含列表的Word单元格未正确复制到Excel中:
我也尝试过以下方法:
worksheet.Cells[row, col] = table.Cell(row, col).Range.FormattedText;
但我得到了相同的结果。
我还尝试通过使用“仅保留文本”复制和粘贴来转换Word文件中的列表,以删除Word的自动格式,并手动删除选项卡。这产生了这个结果:
虽然我可以获得带有列表编号的文本,但我没有得到回车,换行符或换行符来分隔列表中的项目。
至少,我想保留列表编号和换行符,而不必手动剪切/粘贴Keep Text Only;我想避免解析列表编号(可能是数字或字母)和插入换行符的文本。
实现所述结果涉及多个问题:
以下一些示例代码负责所有三次转换。 (注意:这是VBA代码,我已经转换了我的头脑,所以要小心语法“gotchas”)
Word.Range rng = table.Cell[rowCounter, colCounter].Range;
//convert the numbers to plain text, then undo the conversion
rng.ListFormat.ConvertNumbersToText();
string cellContent = rng.Text;
objDoc.Undo(1);
//remove end-of-cell characters
cellContent = TrimCellText2(cellContent);
//replace remaining paragraph marks with the Excel new line character
cellContent.Replace((char)13, (char)10);
worksheet.Cells[rowCounter, colCounter].Value = cellContent;
//cut off ANSI 13 + ANSI 7 from the end of the string coming from a
//Word table cell
private string TrimCellText2(s As String)
{
int len = s.Length;
while (len > 0 && s.Substring(len - 1) == (char)13 || s.Substring(len - 1) == (char)7);
s = s.Substring(0, Math.Min(len-1, len));
return s;
}
在Cindy Meister的帮助下,结合Paul Walls在replacing characters in a C# string的另一个问题中的回答,这是最终的答案。
foreach (Microsoft.Office.Interop.Word.Table table in objDoc.Tables)
{
for (int row = 1; row <= table.Rows.Count; row++)
{
for (int col = 1; col <= table.Columns.Count; col++)
{
// Convert the formatted list number to plain text, then undo the conversion
table.Cell(row, col).Range.ListFormat.ConvertNumbersToText();
string cellContent = table.Cell(row, col).Range.Text;
objDoc.Undo(1);
// remove end-of-cell characters
cellContent = trimCellText2(cellContent);
// Replace remaining paragraph marks with the excel newline character
char[] linefeeds = new char[] { '\r', '\n' };
string[] temp1 = cellContent.Split(linefeeds, StringSplitOptions.RemoveEmptyEntries);
cellContent = String.Join("\n", temp1);
// Replace tabs from the list format conversion with spaces
char[] tabs = new char[] { '\t', ' ' };
string[] temp2 = cellContent.Split(tabs, StringSplitOptions.RemoveEmptyEntries);
cellContent = String.Join(" ", temp2);
worksheet.Cells[row, col] = cellContent;
}
}
}
private static string trimCellText2(string myString)
{
int len = myString.Length;
string charString13 = "" + (char)13;
string charString7 = "" + (char)7;
while ((len > 0 && myString.Substring(len - 1) == charString13) || (myString.Substring(len - 1) == charString7))
myString = myString.Substring(0, Math.Min(len - 1, len));
return myString;
}
以下是Excel中的结果输出:Excel Output