【问题标题】:Apply OpenXML excel number formatcode to string value in C#将 OpenXML excel 数字格式代码应用于 C# 中的字符串值
【发布时间】:2014-08-13 00:07:51
【问题描述】:

在 C# 中使用 OpenXML,有人知道如何应用 excel 数字格式代码 - 例如 (* #,##0.00);(* (#,##0.00); (* "-"??);(@_) - 转成字符串值?

例如,如果我有一个值“10.52982”,我应该得到“10.53”

谢谢

PS 我不想使用提供 WorksheetFunction.Text 函数的 Microsoft.Office.Interop.Excel 程序集

【问题讨论】:

标签: c# excel openxml


【解决方案1】:

试试这个:

    //Create Document
    SpreadsheetDocument googleSpreadSheet = SpreadsheetDocument.Create(GoogleSpreadhSheetStream, SpreadsheetDocumentType.Workbook);
    WorkbookPart cWorkbookPart = googleSpreadSheet.AddWorkbookPart(); 

    //Create stylesheet
    WorkbookStylesPart spStyles = cWorkbookPart.AddNewPart<WorkbookStylesPart>();
    spStyles.Stylesheet = new Stylesheet();
    spStyles.Stylesheet.NumberingFormats = new NumberingFormats();

    uint iExcelIndex = 164;
    //Create format
    NumberingFormat nf2decimal = new NumberingFormat();
    nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);//UInt32Value.FromUInt32(iExcelIndex++);
    nf2decimal.FormatCode = StringValue.FromString("0.00");
    spStyles.Stylesheet.NumberingFormats.Append(nf2decimal);

    //Create cellFormat 
    CellFormat numFormat = new CellFormat();
    numFormat.FormatId = 0;
    numFormat.FillId = 0;
    numFormat.BorderId = 0;
    numFormat.FormatId = 0;
    numFormat.NumberFormatId = nf2decimal.NumberFormatId;
    numFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);

    //Apped cellformat for cells                   
    spStyles.Stylesheet.CellFormats.AppendChild<CellFormat>(cellFormat);
    //update styles and format count
    spStyles.Stylesheet.NumberingFormats.Count = UInt32Value.FromUInt32((uint)spStyles.Stylesheet.NumberingFormats.ChildElements.Count);
    spStyles.Stylesheet.CellFormats.Count = UInt32Value.FromUInt32((uint)spStyles.Stylesheet.CellFormats.ChildElements.Count);

    //save the changes to the stylesheet
    spStyles.Stylesheet.Save();
    googleSpreadSheet.WorkbookPart.Workbook.Save();

并且在设置单元格的值时,使用格式索引。由于我只是加了一个,格式索引应该是1

     SheetData cSheetData = (SheetData)GetWorkSheet(sheetId).Where(x => x.LocalName == "sheetData").First();
     Row currentRow = new Row();
     Cell cell = new Cell();
     currentRow.RowIndex = Convert.ToUInt32(cSheetData.ChildElements.Count()) + 1;
     cell.DataType = new EnumValue<CellValues>(CellValues.Number);
     cell.CellValue = new CellValue(value.Value);
     cell.StyleIndex = 1;
     cell.CellReference = nextCol + rowIndex;
     currentRow.AppendChild(cell);
     cSheetData.Append(currentRow);


     GetWorkSheet(sheetId).Save(); //this returns the reference to my sheet doc to save it

希望对你有所帮助

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多