当我尝试在kendo ui grid中导出数据时,我遇到了奇怪的问题.....
错误:
An exception of type 'System.ArgumentException' occurred in System.Xml.dll but was not handled in user code
Additional information: ' ', hexadecimal value 0x07, is an invalid character.
以下方法我用于导出到excel
private static void WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart)
{
OpenXmlWriter writer = OpenXmlWriter.Create(worksheetPart);
writer.WriteStartElement(new Worksheet());
writer.WriteStartElement(new SheetData());
string cellValue = "";
int numberOfColumns = dt.Columns.Count;
bool[] IsNumericColumn = new bool[numberOfColumns];
string[] excelColumnNames = new string[numberOfColumns];
for (int n = 0; n < numberOfColumns; n++)
excelColumnNames[n] = GetExcelColumnName(n);
uint rowIndex = 1;
writer.WriteStartElement(new Row { RowIndex = rowIndex });
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
DataColumn col = dt.Columns[colInx];
AppendTextCell(excelColumnNames[colInx] + "1", col.ColumnName, ref writer);
IsNumericColumn[colInx] = (col.DataType.FullName == "System.Decimal") || (col.DataType.FullName == "System.Int32") || (col.DataType.FullName == "System.Double") || (col.DataType.FullName == "System.Single");
}
writer.WriteEndElement();
double cellNumericValue = 0;
foreach (DataRow dr in dt.Rows)
{
++rowIndex;
writer.WriteStartElement(new Row { RowIndex = rowIndex });
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
cellValue = dr.ItemArray[colInx].ToString();
if (IsNumericColumn[colInx])
{
cellNumericValue = 0;
if (double.TryParse(cellValue, out cellNumericValue))
{
cellValue = cellNumericValue.ToString();
AppendNumericCell(excelColumnNames[colInx] + rowIndex.ToString(), cellValue, ref writer);
}
}
else
{
AppendTextCell(excelColumnNames[colInx] + rowIndex.ToString(), cellValue, ref writer);
}
}
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
}
private static void AppendTextCell(string cellReference, string cellStringValue, ref OpenXmlWriter writer)
{
writer.WriteElement(new Cell { CellValue = new CellValue(cellStringValue), CellReference = cellReference, DataType = CellValues.String });
}
在下面提到的方法中我遇到异常错误..
private static void AppendTextCell(string cellReference, string cellStringValue, ref OpenXmlWriter writer)
{
writer.WriteElement(new Cell { CellValue = new CellValue(cellStringValue), CellReference = cellReference, DataType = CellValues.String });
}
任何人都可以帮助您在导出到Excel数据时如何克服此错误....
非常感谢...
答案 0 :(得分:4)
XML几乎可以处理任何字符,但是它有范围,控制代码等,它不会胜任。
您最好的选择是,如果您无法让他们确定输出,那就是清理您正在接收的原始数据。您需要使用您记下的字符引用格式替换非法字符。
xml代码中有很多符号。为了替换它们,我们可以使用Reqex.Replace
static string ReplaceHexadecimalSymbols(string txt)
{
string r = "[\x00-\x08\x0B\x0C\x0E-\x1F\x26]";
return Regex.Replace(txt, r,"",RegexOptions.Compiled);
}
答案 1 :(得分:1)
x26是&符号&amp;&#39;字符 - 这可以用&#39;&amp;&#39;编码。这样它就出现在你的Excel表格中。