Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c# - How to format cells in excel sheet programmatically?

We have an asp.net c# program that reads a sheet from an Excel file and writes it out in a new sheet (also adding one column if data come from a Sql Server table).

Issue: in the new sheet the data is not formatted as we want. For example we want date without time and left-aligned, but they're formatted with the time and right-aligned, etc.

How can we format an Excel cell?

This is our code:

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just set the appropriate property on your cell (Range) objects.

Set NumberFormat to control the cell number formatting, i.e.:

newSheet.Cells[i, j].NumberFormat = "m/d/yyyy"

Set HorizontalAlignment to control the alignment, i.e.:

newSheet.Cells[i, j].HorizontalAlignment = ExcelAlignment.xlLeft; //or Excel.XlHAlign.xlHAlignLeft

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...