I am currently using NPOI to generate Excel files based on a database from my asp.net mvc app. I'm almost done with the code, except one small issue which I keep getting when when trying to write Dates to Excel.
In the database (MS SQL Server) I have the date saved as 41883, 41913 etc ... which in C# I can convert to a DataTime object using
DateTime dt = DateTime.FromOADate(Convert.ToDouble(41883));
The code that I use to write the Date to Excel looks lie this:
var cell = excelRow.CreateCell(columnIndex);
IDataFormat format = workbook.CreateDataFormat();
short dateFormat = format.GetFormat("dd/MM/yyyy");
cell.SetCellValue(DateTime.FromOADate(Convert.ToDouble(dbDateValue)));
ICellStyle cellStyle = workbook.CreateCellStyle();
cellStyle.DataFormat = dateFormat;
cell.CellStyle = cellStyle;
this is just a sample of my code (the piece which is doing the date writing part).
The issue with this piece of code is that only part of the date cells are actually formatted as a date, for all the others I still see the values as in the database 41883, 41913 etc which of course I can select and apply Short Date/Date formatting from Excel (but I don't want that).
Could anyone let me know why such a behavior could appear (formatting works only for part of the cells)... I even tried to use the HSSFDataFormat.GetBuiltinFormat("Date") but none of the cells were formatted in that case.
The image above explains better my issue... when I select the first cells in the first column I see the cell is formatted as "Custom"... for all the other values which are not formatted it's General. Once I select the cells I can format it as date from Excel without any problem. This is weird as the same code is executed for all the date cells, but only some get the proper formatting...
No need to convert anything.
You have to create a style and apply it to your cell
var newDataFormat = workbook.CreateDataFormat();
var style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.DataFormat = newDataFormat.GetFormat("MM/dd/yyyy HH:mm:ss");
foreach (var objArticles in tempArticles)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber++);
//Set the Values for Cells
row.CreateCell(0).SetCellValue(objArticles.ProjectId);
row.CreateCell(1).SetCellValue(objArticles.ProjectName);
row.CreateCell(2).SetCellValue(objArticles.MetricDescription);
row.CreateCell(3).SetCellValue(objArticles.MetricValue);
var cell = row.CreateCell(4);
cell.SetCellValue(objArticles.BuildDate);
cell.CellStyle = style;
var cell5 = row.CreateCell(5);
cell5.SetCellValue(objArticles.CreateDate);
cell5.CellStyle = style;
}
Related
In C# I have populated an excel file with data. Now I would like to create a table starting at cell A2.
I am using the code below to create the table but instead of creating the table starting at Cell A2, the table is being created starting at cell A3
using var package = new ExcelPackage(file);
var ws = package.Workbook.Worksheets.Add(Name: "MainReport");
var range = ws.Cells[Address: "A2"].LoadFromCollection(people, PrintHeaders: true);
range.AutoFitColumns();
//Formats Header row
ws.Cells[Address: "A1"].Value = "My Data!";
ws.Cells[Address: "A1:C1"].Merge = true;
ws.Column(col: 1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Row(row: 1).Style.Font.Size = 24;
ws.Row(row: 1).Style.Font.Color.SetColor(Color.Pink);
ws.Row(row: 2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
ws.Row(row: 2).Style.Font.Bold = true;
ws.Column(col: 3).Width = 20;
//create a range for the table
ExcelRange range_table = ws.Cells[2, 1, ws.Dimension.End.Row, ws.Dimension.End.Column];
//add a table to the range
ExcelTable tab = ws.Tables.Add(range_table, "Table1");
//format the table
tab.TableStyle = TableStyles.Medium2;
Excel itself works so that if you select A2:C4 and create a table and you say "has no Headers" it will put some generic headers in A2:C2 and shift the data area (and the data if there is any) to A2:C5.
If you say "has Headers" the headers will be defined in A2:C2, too, but the data only is in A3:C4.
The real Excel obviously does some guessing whether headers are present or not and pre-ticks the box for you.
As stated here in the API Documentation, there is no flag to define if headers are present in the range so there might be no guessing and it might be assumed it is "no" and the shifting as explained on top takes place.
If you take that into consideration you should be able to work it out.
I'm working with DataGridView and excel interop. I have access file where are column date and column time. With SQL I create new column DateTime which I then show in dgv.
SELECT
FORMAT(DateOS, 'dd.MM.yyyy') AS DateOS,
FORMAT(TimeOS, 'hh:mm:ss') AS TimeOS,
FORMAT(DateOS+TimeOS, 'dd.MM.yyyy HH:mm:ss') AS DateTimeOS
FROM [table]
Then I select whole column DateTimeOS and copy it to clipboard.
After this I PasteSpecial to Excel file which has prepared format of column.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Workbook excelExportFile;
Excel.Worksheet wsExport;
wsExport = excelExportFile.Worksheets["Data"];
dviewAll.ColumnHeadersVisible = false;
dviewAll.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;
dviewAll.Columns[columnNameDateTime].Selected = true;
DataObject data = dviewAll.GetClipboardContent();
if(data != null)
Clipboard.SetDataObject(data, true);
dviewAll.ColumnHeadersVisible = true;
wsExport.Cells[2, 2].PasteSpecial();
Result is first cell is formated as string, rest is formated as datetime.
picture
When I open this string cell and just press enter, it will format to datetime as rest.
Any ideas, how to prevent this issue, or how to programically open cell and press enter?
UPDATE:
First suggestion from Excel treating date column as general when exporting to Excel using C# gives me exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The name
'Format' is bound to a method and cannot be used like a property'
And for the second one: Excel.Worksheet does not have "Column" property.
I have a vsto application that populates an Excel sheet.
First I populate the datatable. The next function is to create a vsto listobject:
// Populate the sheet
XlsInterop.Excel.Worksheet worksheet = (XlsInterop.Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add();
extendedWorksheet = Globals.Factory.GetVstoObject(worksheet);
XlsInterop.Excel.Range cell = extendedWorksheet.Range["A1"];
excelItemsList = extendedWorksheet.Controls.AddListObject(cell, sheetName);
excelItemsList.AutoSetDataBoundColumnHeaders = true;
excelItemsList.DataSource = dt;
excelItemsList.ListColumns[5].Range.NumberFormat = "#";
Now the problem is that in column "5" I have values like 005, 004. In Excel, the values display as 5 and 4. How can I make sure that the values in Excel show the same values as in my database?
If I change my code like:
excelItemsList.SetDataBinding(dt);
excelItemsList.ListColumns[5].Range.NumberFormat = "#";
excelItemsList.SetDataBinding(dt);
It is doing what I want, but I don't think that this is the way to go.
If you know how many leading zeros you need, you can then format the column with that.
.NumberFormat = "000";
The column would then still be evaluated as a number.
I have excel template with empty one-column table. I need to populate it with some string values (this is needed for setting lookups using data validation, but I guess it doesn't really matter)
I came up to getting Table object and I assume I should use Append method
var workBookPart = doc.WorkbookPart;
var lookupsSheet = (Sheet)workBookPart.Workbook.Sheets.FirstOrDefault(x => (x is Sheet && ((Sheet)x).Name == "Lookups"));
var worksheetPart = (WorksheetPart)workBookPart.GetPartById(lookupsSheet.Id);
var table = worksheetPart.TableDefinitionParts.FirstOrDefault(x => x.Table.DisplayName == "ValuesTable")?.Table;
Can someone enlighten about the correct way of adding rows to such table. Thanks!
I would suggest you use the ClosedXML library to set the values of cells in your worksheet. By using ClosedXML, you will be able to populate the cells you want in the following fashion:
var workbook = new XLWorkbook();
var ws = workbook.Worksheets.Add("Demo");
// Set the values for the cells
ws.Cell(1, 1).Value = "Value";
ws.Cell(2, 1).Value = 1;
ws.Cell(3, 1).Value = 2;
ws.Cell(4, 1).Value = 3;
ws.Cell(5, 1).Value = true;
Note that you can set the value of a cell to a string, an integer, and a boolean without doing any explicit casting. You can set the value of a cell without doing any explicit casting to other types as well, as it is explained in the following link: Cell Values.
For more information regarding the ClosedXML library please refer to the documentation.
As a side note, I was really eager to use Open XML to manipulate Excel spreadsheets but I found ClosedXML way easier to use.
Please help me to fetch or to read specific cell data of .xls spreed sheet using GemBox in c#.
I am able to write but fails to read the specific cell data.
I don't want to read all data at once.
var dataSet = new DataSet();
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
GemBox.Spreadsheet.ExcelFile ef = new GemBox.Spreadsheet.ExcelFile();
// ExcelFile ef = ExcelFile.Load(#"C:\Users\LENOVO\Documents\100sitesSpreedSheet.xls");
ef = GemBox.Spreadsheet.ExcelFile.Load(#"C:\Users\LENOVO\Documents\100sitesSpreedSheet.xls");
ExcelWorksheet ws = ef.Worksheets["100sitesSpreadSheet"];
ws.Cells[6, 0].Value = "abcd";
ef.Save(#"C:\Users\LENOVO\Documents\100sitesSpreedSheet.xls");
to read the specific cell's value you can just use the Value property, like the following:
Console.WriteLine(ws.Cells["A7"].Value);
This property is of an object type and can return a text or a number or a date, depending on the data it stores. Also note that GetFormattedValue method actually converts that value into a string representation by using a number format which is applied to that cell.