OpenXML电子表格 - 写入单元格值时保留值前后的空格

6
我正在使用OPENXML SDK 2.0来流式传输电子表格文件。源数据来自数据表,然后使用openxml将其写入电子表格。如果数据表中的某一列数据具有 " Treshold%"(该文本在前面有制表符空格),则会将其写入 Excel 中,但在 Excel 单元格中将其写为 "Treshold%" 并删除制表符空格。
我正在使用以下代码。使用workSheetWriter.PasteTextworkSheetWriter.PasteValue方法。
WorksheetWriter workSheetWriter = new WorksheetWriter(spreadSheet, workSheet);

int intValue = 0;
if (strValue.Contains("$"))
{
    strValue = strValue.Replace("$", "");
    strValue = strValue.Replace(",", "");

    workSheetWriter.PasteValue(cellLocation, strValue, CellValues.Number);
}
else if (int.TryParse(strValue, out intValue))
{
    workSheetWriter.PasteValue(cellLocation, strValue, CellValues.Number);
}
else if (string.IsNullOrEmpty(strValue))
{
    workSheetWriter.PasteText(cellLocation, strValue);
}
else
{
    workSheetWriter.PasteText(cellLocation, strValue);
}

请帮忙解决这个问题。如何将以一个制表符( Treshold%)开头的数值写入Excel单元格,使其保持相同的格式?

1个回答

6

我正在使用OPENXML SDK 2.0

由于在OpenXML SDK 2.0中没有workSheetWriter类,我猜测你正在使用这个库:Simple OOXML

虽然我没有使用过这个库,但是:

我认为你不能使用这些方法,因为.PasteText.PasteValue方法使用CellValues.StringCellValue存储文本,这会导致空格被忽略:

{
    cell.CellValue = new CellValue(value);
    cell.DataType = new EnumValue<CellValues>(type);
}

仅使用OPENXML SDK 2.0,我可以通过使用CellValues.InlineString类型、InlineStringText类来实现您想要的功能(保留空格):

Text text1 = new Text
{
    Text = " Text with space at beginning",
    Space = SpaceProcessingModeValues.Preserve
};

cell.InlineString = new InlineString(text1);
cell.DataType = new EnumValue<CellValues>(CellValues.InlineString);

如果有人需要更多代码的示例,请参考以下链接:https://blogs.msdn.microsoft.com/wriju/2016/03/13/open-xml-create-excel-from-scratch。注意:此示例未设置“保留”设置,这是保留间距所必需的。您需要修改“Text t = new Text();”这一行为“Text t = new Text() { Space = SpaceProcessingModeValues.Preserve };”。 - joeshmoe301

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接