[英]How can we change the Datatype of the Excel cell to CellValues.String from c#
[英]How can we specify the columns DataType to string, number Datetime in Excel/SpreadSheet when Export from c#
我正在使用以下代碼從c#將數據導出到Excel。 我將為此提供一個示例圖像,以更好地了解我所需要的。
不能僅針對單個列,我們不能說這種類型即將進入excel中的特定列。 在導出不同數據期間
正在使用的代碼是
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
Create(savingFileName, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
worksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
var bold1 = new System.Windows.Documents.Bold();
DocumentFormat.OpenXml.Spreadsheet.CellFormat cf = new DocumentFormat.OpenXml.Spreadsheet.CellFormat();
// Add Sheets to the Workbook.
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets;
sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.
GetIdOfPart(worksheetPart),
SheetId = sheetId,
Name = "Sheet" + sheetId
};
sheets.Append(sheet);
//Add Header Row.
var headerRow = new Row();
headerRow.RowIndex = 10;
var cell=new Cell();
foreach (DataColumn column in dtCollection.Columns)
{
cell = new Cell
{
DataType = CellValues.String, CellValue = new CellValue(column.ColumnName.ToUpper())
};
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (DataRow row in dtCollection.Rows)
{
var newRow = new Row();
foreach (DataColumn col in dtCollection.Columns)
{
cell = new Cell
{
DataType = CellValues.String,
CellValue = new CellValue(row[col].ToString())
};
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
在上面的這張圖片中,您可以看到“借方和貸方”列應該是數字,但對於我的代碼,它只能是字符串
列類型
根據上述要求,我需要將數據表導出到excel中,而excel中的每一列都應是不同的數據類型。 我該怎么辦才能幫助我完成我的工作
好的,這是我可以快速提出的兩個選擇。
這是第一個選項的示例:使用字典來查找應將哪種數字格式注入到每一列中。
var headerFormatMap = new Dictionary<string, string>(); // <columnHeader, NumberFormat>
// i.e fill it like this
headerFormatMap.Add("TransactionDate", "MM/DD/YYYY");
headerFormatMap.Add("Debit", "##.000"); // Display 37.75 as 37.750.
像這樣給所有可能的列設置格式。 當需要導出時,獲取正確的numberFormat並將其插入其列中:
// Assuming your first row is header. (I remember excel indexes start from 1)
// Do this foreach column
Range range = (Excel.Range)worksheetobject.Cells[1,1];
var header = (string)range.Value;
range.EntireColumn.NumberFormat = headerFormatMap[header];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.