OpenXML - Writing a date into Excel spreadsheet results in unreadable content

前端 未结 7 820
离开以前
离开以前 2020-12-10 11:21

I am using the following code to add a DateTime to a column in my spreadsheet:

var dt = DateTime.Now;
r.AppendChild(new Cell()
    {         


        
7条回答
  •  死守一世寂寞
    2020-12-10 12:03

    Try indicating it is a CellValues.String type, instead of a CellValues.Date type.

    Use

    DataType = new EnumValue(CellValues.String)   // good
    

    instead of

    DataType = new EnumValue(CellValues.Date)     // bad
    

    Now, it would make sense to add it as date, without the ToString()conversion, and use the CellValues.Date DataType -- but CellValue() only takes a string as a parameter.

    [Why, OpenXmlSDK, WHY??? You're a wrapper. Wrap things nicely. Make them invisible, and make my life easier. :::sigh:::]

    Additionally, if the target cell expects to be formatting a date, we should be indicating it is a date.

    But I've found that while CellValues.String and CellValues.Date both get formatted as expected (identically), only the CellValues.Date throws up the "unreadable content" on-load.

    I've had utterly no luck with any variation on dt.ToOADate().ToString(new CultureInfo("en-US")); method -- I end up with a five-digit number that gets displayed in the spreadsheet as five-digit number, when it should be a formatted date.

    I was receiving the same error message when adding a string value, but using the CellValues.Number DataType.

提交回复
热议问题