Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenXML Spreadsheet- Preserve space before or after the value when writing a cell value

I am using OPENXML SDK 2.0 to stream the spread sheet file. The source data is come from data table and writing this to Spreadsheet using openxml. If there is a one of the column data of a data table has " Treshold%" (this text has tab space on it preceding) and the same being written excel but which is writing it to "Treshold%" in excel cell and removing the tab space.

I am using the code as below. Using workSheetWriter.PasteText and workSheetWriter.PasteValue methods.

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);
}

Please help on this. How can write the value which a tab space in the begining ( Treshold%) into excel cell as same format ?

like image 747
user2390252 Avatar asked May 16 '13 14:05

user2390252


1 Answers

I am using OPENXML SDK 2.0

Since there is no workSheetWriter class in OpenXML SDK 2.0, I guess you are using this library: Simple OOXML

I don't use this library but,

  • from the code I see in browserCode on CodePlex,
  • according to my testing,
  • and according to this SO question What is the difference between CellValues.InlineString and CellValues.String in OpenXML?,

I think you can't by using these methods, since the .PastText and .PasteValue methods are storing text by using CellValues.String and CellValue, and this causes that the space is ignored:

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

By using OPENXML SDK 2.0 only, I am able to accomplish what you want (preserve space) by using CellValues.InlineString type, InlineString and Text class:

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);
like image 50
Chris Avatar answered Oct 11 '22 09:10

Chris