我正在尝试通过代码将 MS Word 表格转换为 HTML。我正在调整 this answer 中给出的一些代码但我需要最终将生成的 HTML 表转换为 CALS 表格式,然后与我的程序生成的现有 XML 树合并。
我目前正在处理从 Word 表格到 HTML 表格部分的转换(在将其转换为 CALS 之前),但我的问题似乎是一个反复出现的错误,它说:
hexadecimal value 0x07, is an invalid character
果然,如果我在程序运行时通过消息框查看表格中每个单元格生成的 HTML,我可以看到在表格单元格的文本之后有一个小“框”。
我试过用类似的东西
string newContent = content.Replace((char)(0x1F), Convert.ToChar(""));
替换字符,但它会提示字符串必须是一个字符长。
在我尝试将 HTML 存储在 XElement 中的意义上,我可能会以错误的方式处理事情。但我不认为这是导致问题的原因?!
问题显然是 Word 表格单元格中的小“框”,但不确定它是什么或如何忽略或删除它。
这是我的代码
private void dealWithTables()
{
try
{
foreach (Table tb in doc.Tables)
{
for (int r = 1; r <= tb.Rows.Count; r++)
{
for (int c = 1; c <= tb.Columns.Count; c++)
{
try
{
Cell cell = tb.Cell(r, c);
foreach (Paragraph paragraph in cell.Range.Paragraphs)
{
Tagging2(paragraph.Range, "P", paragraph.Range.Text);
}
Tagging2(cell.Range, "TD");
}
catch (Exception e)
{
if (e.Message.Contains("The requested member of the collection does not exist."))
{
//Most likely a part of a merged cell, so skip over.
}
else throw;
}
}
try
{
Row row = tb.Rows[r];
Tagging2(row.Range, "TR");
}
catch (Exception ex)
{
bool initialTrTagInserted = false;
int columnsIndex = 1;
int columnsCount = tb.Columns.Count;
while (!initialTrTagInserted && columnsIndex <= columnsCount)
{
try
{
Cell cell = tb.Cell
(r, columnsIndex);
//cell.Range.InsertBefore("<TR>");
initialTrTagInserted = true;
}
catch (Exception e)
{
}
columnsIndex++;
}
columnsIndex = tb.Columns.Count;
bool endTrTagInserted = false;
while (!endTrTagInserted && columnsIndex >= 1)
{
try
{
Cell cell = tb.Cell(r, columnsIndex);
//cell.Range.InsertAfter("</TR>");
endTrTagInserted = true;
}
catch (Exception e)
{
}
columnsIndex--;
}
}
}
Tagging2(tb.Range, "Table");
object separator = "";
object nestedTable = true;
tb.ConvertToText(separator, nestedTable);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
XElement tableTree = new XElement("table");
public void Tagging2(Range range, string tagName, string content)
{
string newContent = content.Replace((char)(0x1F), Convert.ToChar(""));
tableTree.Add(new XElement(tagName, newContent));
MessageBox.Show("text of para " + newContent);
}
public void Tagging2(Range range, string tagName)
{
tableTree.Add(new XElement(tagName));
}
最佳答案
似乎您正在用空字符串替换它,因此您的错误消息。尝试用空格替换它:
content.Replace((char)(0x07), (char)(0x20))
关于c# - 十六进制值 0x07,是无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439103/