.NET - Excel file generated via data table - where

2019-08-19 11:54发布

We have a process to return results of a search, and export the data to Excel. It's converting the results to a data table, and adding the data table to a blank worksheet:

var wb = new XLWorkbook();
wb.Worksheets.Add(ds);
return wb;

The users want some formatting added to the sheet - setting date fields to display as MM/DD/YYYY, for example.

Can't find the right reference to get to the worksheet in the new workbook, however.

Also unsure if one can set a format to a column, as opposed to the code below which I think is converting it to a string,

((Excel.Range)sheet.Cells[i, 2]).EntireColumn.NumberFormat = "yyyy-MM-dd";
sheet.Cells[i, 2].Value2 = Convert.ToDateTime(dr["date"].ToString());

Anyone?

EDIT - @ScottHannen identified the library I should be investigating, and I've made more progress. I have drilled into the worksheets and successfully added the formatting, but it's not reflecting as such in the final document.

Here's the code:

var wb = new XLWorkbook();
wb.Worksheets.Add(ds);
foreach (IXLWorksheet ws in wb.Worksheets)
     {
         if (value == 1)
         {
               ws.Column(16).Style.DateFormat.Format = "yyyy-MM-dd";
               ws.Column(17).Style.DateFormat.Format = "yyyy-MM-dd";
          }
          else
                { }
      }

    return wb;

When I look at the final document, the dates are still displaying as verbose - 12/7/2017 12:00:00 AM - but the formatting IS in the document. If I do the manual "hit enter in the cell and exit" thing, the formatting updates, as does doing Text to Columns.

Of course, I don't WANT to do that, I want the formatting to take straight away.

I assume the issue is that I'm adding the data first and formatting it after, just like a regular sheet. But is there a command in there to refresh/apply/what have you the formatting?

标签: c# excel
0条回答
登录 后发表回答