Office
A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.
1,696 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
How to insert currency into DocumentFormat OpenXml Spreadsheet
Create a New Spreadsheet with Currency Formatting
Example Code :
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class Program
{
public static void Main()
{
// Create a new spreadsheet document.
using (SpreadsheetDocument document = SpreadsheetDocument.Create("CurrencyExample.xlsx", SpreadsheetDocumentType.Workbook))
{
// Add a WorkbookPart and WorksheetPart
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Create a Stylesheet
WorkbookStylesPart stylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = new Stylesheet(
new Fonts(new Font()), // Default font
new Fills(new Fill()), // Default fill
new Borders(new Border()), // Default border
new CellFormats(
new CellFormat(), // Default cell format
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Right })
{
NumberFormatId = 14, // Currency format
ApplyNumberFormat = true
}
)
);
stylesPart.Stylesheet.Save();
// Add a SheetData to the Worksheet
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
Row row = new Row();
Cell cell = new Cell()
{
CellValue = new CellValue("1234.56"),
DataType = CellValues.Number,
StyleIndex = 1 // Apply the currency style (index 1 in this case)
};
row.AppendChild(cell);
sheetData.AppendChild(row);
// Add a Worksheet to the Workbook
Sheets sheets = document.WorkbookPart.Workbook.GetFirstChild<Sheets>();
Sheet sheet = new Sheet()
{
Id = document.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet1"
};
sheets.Append(sheet);
document.WorkbookPart.Workbook.Save();
}
}
}