我们有一个asp.net c#程序,它从Excel文件中读取一个工作表并将其写入一个新工作表(如果数据来自Sql Server表,还会添加一个列)。
问题:在新工作表中,数据未按我们的要求格式化。例如,我们想要没有时间的日期和左对齐,但它们的格式是时间和右对齐等。
我们如何格式化Excel单元格?
这是我们的代码:
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = worksheetName;
for (int i = 0; i < headerList.Count; i++)
{
newSheet.Cells[1, i + 1] = headerList[i];
Range headerRange = newSheet.Cells[1, headerList.Count]; ;
headerRange.Font.Bold = true;
}
for (int i = 0; i < listDrugOrder.Count; i++)
{
DrugOrder drugorder = listDrugOrder[i];
newSheet.Cells[i + 2, 1] = drugorder.RES_ID;
newSheet.Cells[i + 2, 2] = drugorder.STATION;
newSheet.Cells[i + 2, 3] = drugorder.DATE;
newSheet.Cells[i + 2, 4] = drugorder.DRUG;
newSheet.Cells[i + 2, 5] = drugorder.NDC;
newSheet.Cells[i + 2, 6] = drugorder.UNITS_PER_DOSE;
newSheet.Cells[i + 2, 7] = drugorder.FORM;
newSheet.Cells[i + 2, 8] = drugorder.ROUTE;
newSheet.Cells[i + 2, 10] = drugorder.FREQUENCY;
newSheet.Cells[i + 2, 11] = drugorder.Heading_LAKE_ORDERS;
newSheet.Cells[i + 2, 12] = drugorder.HOA;
newSheet.Cells[i + 2, 13] = drugorder.INSTRUCTIONS;
newSheet.Cells[i + 2, 14] = drugorder.DIAGNOSIS;
newSheet.Cells[i + 2, 15] = drugorder.DIAGNOSIS_CODES;
newSheet.Cells[i + 2, 16] = drugorder.MAR;
newSheet.Cells[i + 2, 17] = drugorder.TAR;
newSheet.Cells[i + 2, 18] = drugorder.DRUG_ALERT;
}
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
答案 0 :(得分:17)
只需在单元格(范围)对象上设置the appropriate property。
设置NumberFormat以控制单元格number formatting,即:
newSheet.Cells[i, j].NumberFormat = "m/d/yyyy"
设置HorizontalAlignment以控制对齐,即:
newSheet.Cells[i, j].HorizontalAlignment = ExcelAlignment.xlLeft; //or Excel.XlHAlign.xlHAlignLeft