Date column is not set properly in open XML Excel - c#

I am trying to copy the data in excel sheet but it does not show properly it is show like ####### but I want 17-09-2016 like this.kindly suggest me what code I am write to export the excel in proper format.
Code:
var rngTable2 = ws.Range("A:G");
var rngHeaders2 = rngTable2.Range("F4:G4");
rngHeaders2.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.General;
rngHeaders2.Style.Alignment.Vertical = XLAlignmentVerticalValues.Bottom;
Date comes from this code:
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString("dd/MM/yyyy")).Value = myVal1;
index5++;

Ultimately, it seems like you're trying to get a date from a label and then put this value into a load of cells within column F somewhere. I'm guessing you have this within a for loop as well seeing as you're incrementing index5. So something like this should work:
//Make column F a date column. Alter to a specific range if the whole column shouldn't be of date type.
Range rg = ws.Range("F:F");
rg.EntireColumn.NumberFormat = "DD/MM/YYYY";
var lblpkgdate = (Label).gvvessel.Rows[j].FindControl("lblpackagedate");
//Convert lblpkgdate text to DateTime object assuming format of dd/MM/yyyy to ensure it is actually a date.
DateTime pkgDate = DateTime.ParseExact(lblpkgdate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
for(int i = 1, i < YourMaxRowValue, i++)
{
ws.Cell("F" + i).Value = pkgDate;
}
NOTE - I've altered index5 to 'i' as this is less misleading if you're looping. I've also altered myVal1 to pkgDate as I think this is more meaningful.

you can use NumberFormat
Label lblpkgdate = (Label)gvvessel.Rows[j].FindControl("lblpackagedate");
string myVal1 = lblpkgdate.Text;
ws.Cell("F" + index5.ToString()).Style.NumberFormat.Format = "DD-MM-YYYY";
ws.Cell("F" + index5.ToString()).Value = myVal1;
index5++;

Related

NPOI doesn't apply format to .xls

C#, NPOI
Good evening, i'm trying to fill in an empty template with values(numbers, but in string variable), that needs to be in cells.
So, when it came to formatting, i've stuck with styling. That means, when i wrote the value inside(in pre-formatted cell) i get just the string value, that was in array.
But, when i open file, click "edit cell", then apply without any changes, then cell is formatted, with the format, which was in a template
I tried to apply previous style in cell(basically just copy style in var, before setting a value, then re-apply style), but, it didnt help.
Here is the video of my doings
var cr = new CellReference(cellAndValue[i, 0]);
var row = sheet?.GetRow(cr.Row);
var cell = row?.GetCell(cr.Col);
var prevtype = cell.CellType;
var prevstyle = cell.CellStyle;
var dataformat = cell.CellStyle.DataFormat;
CellType type = cell.CellType;
cell.SetCellValue(cellAndValue[i, 0]);
How to resolve that?)
It was required to convert incoming data to int, before inserting it XD
int n;
if (Int32.TryParse(cellAndValue[i, 1], out n))
{
cell.SetCellValue(n);
}
else
{
cell.SetCellValue(cellAndValue[i, 1]);
}

use the conditional format with epplus

I´m trying to aplly a conditional format to a an Excel using eppplus, in that case i want to apply a pattern to all odd rows. so i try use the mod function, but not working, i don´t know how to put the formula
ExcelAddress _formatRangeAddress = new ExcelAddress("A2:Q" + (listSize+ 1));
string _statement = "MOD(ROW();2)=0";
var _cond1 = hoja.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond1.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond1.Style.Fill.BackgroundColor.Color = System.Drawing.Color.Gray;
_cond1.Formula = _statement;
Check the formula string. I think you want a , instead of that ;. So change this:
string _statement = "MOD(ROW();2)=0";
to this:
string _statement = "MOD(ROW(),2)=0";

Conditional formatting to entire row

I have a code in C# with EPPLUS for Excel that fills a cell green if the value of the cell is over 100. It works:
ExcelAddress _formatRangeAddress = new ExcelAddress("G4:G" + (c.Count + 4));
string _statement = "IF(G4>100,1,0)";
var _cond2 = hoja.ConditionalFormatting.AddExpression(_formatRangeAddress);
_cond2.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
_cond2.Style.Fill.BackgroundColor.Color = System.Drawing.Color.LimeGreen;
_cond2.Formula = _statement;
But what I really need is to fill the entire row. If I change the range:
ExcelAddress _formatRangeAddress = new ExcelAddress("A4:G" + (c.Count + 4));
Applies only for the cells in the A column, not to the entire row.
What I am doing wrong?
Make the reference to G4 absolute otherwise the formula will be apply relative to that cell. So change this line:
string _statement = "IF(G4>100,1,0)";
to apply to the entire row based ONLY on G4
string _statement = "IF($G$4>100,1,0)";
(Response to Comments)
to apply to entire rows relative to row number but keep the column fixed to G:
string _statement = "IF($G4>100,1,0)";

Excel Date column returning INT using EPPlus

So i'm using EPPlus to read and write excel documents.
Workflow
User generates populated excel document
Opens document and adds a row
Uploaded and read
The dates that are generated when I create the document using EPPlus show correctly when I'm reading the value back but the row the user changes the date one or adds is showing as an INT value not something I can use as a real date.
When I enter the date 1/01/2014 and write it, the output when I open the file up shows 41640
I'm reading it as follows
sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value != null
? sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value.ToString().Trim()
: string.Empty
Update
When exporting the file I have added the following
DateTime testDate;
if (DateTime.TryParse(split[i], out testDate))
{
sheet.Cells[row, i + 1].Style.Numberformat.Format = "MM/dd/yyyy";
sheet.Cells[row, i + 1].Value = testDate.ToString("MM/dd/yyyy");
}
Also when reading the value back I have tried
sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Style.Numberformat.Format = "MM/dd/yyy";
I still get an INT back
...when I need to read that excel file, the only dates that are
incorrect are the ones the user has changed
So when you read the modified excel-sheet, the modified dates are numbers whereas the unchanged values are strings in your date-format?
You could get the DateTime via DateTime.FromOADate:
long dateNum = long.Parse(worksheet.Cells[row, column].Value.ToString());
DateTime result = DateTime.FromOADate(dateNum);
With your sample-number:
Console.Write(DateTime.FromOADate(41640)); // -> 01/01/2014
I stumbled upon this issue today when trying to generate some Excel documents from some ASP.NET DataTables: I had no problem with strings, but ran into few issues with numeric types (int, doubles, decimals) and DataTables, which were formatted as string or as numeric representations (OADate).
Here's the solution I eventually managed to pull off:
if (dc.DataType == typeof(DateTime))
{
if (!r.IsNull(dc))
{
ws.SetValue(row, col, (DateTime)r[dc]);
// Change the following line if you need a different DateTime format
var dtFormat = "dd/MM/yyyy";
ws.Cells[row, col].Style.Numberformat.Format = dtFormat;
}
else ws.SetValue(row, col, null);
}
Apparently, the trick was to set the value as DateTime and then configure the proper Style.Numberformat.Formataccordingly.
I published the full code sample (DataTable to Excel file with EPPlus) in this post on my blog.
You should try using
string dateFromExcel = workSheet.Cells[row, col].Text.ToString();
DateTime localdt;
if (DateTime.TryParse(dateFromExcel, out localdt))
{
dateFromExcel = localdt.ToString("MM/dd/yyyy");
};
the Value reads the value in the general formatting while Text reads the value as it is from the excel with applied formatting.
you could check if the cell format is in date format,
then parse it to date
var cell = worksheet.Cells[row, col];
value = cell.Value.ToString();
if (cell.Style.Numberformat.Format == "[$-409]d\\-mmm\\-yy;#")
{
string inputString = DateTime.FromOADate(long.Parse(value.ToString())).ToString("dd-MMM-yyyy");
}
You can also change the 'NumberFormatLocal' property. This worked for me. If you format the Excel file before improting it using EPPLUS.
The following basic example of code formats column A in a typical excel file.
Sub ChangeExcelColumnFormat()
Dim ExcelApp As Excel.Application
Dim ExcelWB As Excel.Workbook
Dim ExcelWS As Excel.Worksheet
Dim formatRange As Excel.Range
Dim strFile As String = "C:\Test.xlsx"
Dim strSheetname As String = "Sheet1"
ExcelApp = New Excel.Application
ExcelWB = ExcelApp.Workbooks.Open(strFile)
strColSelect = "A:A"
strFormat = "dd/mm/yyyy"
formatRange = ExcelWS.Range(strColSelect)
formatRange.NumberFormatLocal = strFormat
ExcelWB.Save()
ExcelWB.Close()
ExcelApp.Quit()
ExcelWS = Nothing
ExcelWB = Nothing
ExcelApp = Nothing
End Sub

"Date Taken" not showing up in Image PropertyItems while it shows in file details (file properties) in Windows Explorer

I'm a little bit surprised and puzzled. I try to read the property items from an image. Particularly, I'm interested in the "Date Taken". I have written a procedure that does exactly that. More or less. With some files it works perfectly, but...
I have some files that have a 'Date Taken' in the properties (when viewed by Windows Explorer, Windows 7 x64). They differ from the date created, modified and accessed. So I do have a 4th date.
However, if I loop through the property items, it does not show up (on any ID).
When I look for it on the PropertyItem.Id (0x9003 or 36867), i get that the property item does not exist.
My Code to loop through the property items:
for (int i = 0; i < fileNames.Length; i++)
{
FileStream fs = new FileStream(fileNames[i], FileMode.Open, FileAccess.Read);
Image pic = Image.FromStream(fs, false, false);
int t = 0;
foreach (PropertyItem pii in pic.PropertyItems)
{
MessageBox.Show(encoding.GetString(pii.Value, 0, pii.Len - 1) + " - ID: " + t.ToString());
t++;
}
}
The code to read only the "Date Taken" property (I stole from here: http://snipplr.com/view/25074/)
public static DateTime DateTaken(Image getImage)
{
int DateTakenValue = 0x9003; //36867;
if (!getImage.PropertyIdList.Contains(DateTakenValue))
return DateTime.Parse("01-01-2000");
string dateTakenTag = System.Text.Encoding.ASCII.GetString(getImage.GetPropertyItem(DateTakenValue).Value);
string[] parts = dateTakenTag.Split(':', ' ');
int year = int.Parse(parts[0]);
int month = int.Parse(parts[1]);
int day = int.Parse(parts[2]);
int hour = int.Parse(parts[3]);
int minute = int.Parse(parts[4]);
int second = int.Parse(parts[5]);
return new DateTime(year, month, day, hour, minute, second);
}
However, when I change the date taken in the 'File properties window' of Windows Explorer, It starts to show up in my program.
So my question is: Where does this "Date Taken" comes from? How can I access it? Could it be that there is another source of information besides the EFIX Data?
Thanks!
you can try something like this if you want to start with some basic coding
// Load an image however you like.
System.Drawing.Image image = new Bitmap("my-picture.jpg");
Referenced from AbbydonKrafts
// Get the Date Created property
//System.Drawing.Imaging.PropertyItem propertyItem = image.GetPropertyItem( 0x132 );
System.Drawing.Imaging.PropertyItem propertyItem
= image.PropertyItems.FirstOrDefault(i => i.Id == 0x132 );
if( propItem != null )
{
// Extract the property value as a String.
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
string text = encoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1 );
// Parse the date and time.
System.Globalization.CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateCreated = DateTime.ParseExact( text, "yyyy:MM:d H:m:s", provider );
}
Well, I am obtaining the "Modified" date of my image file instead of the Date Taken.
I have achieved using the following code:
public static System.DateTime GetImageDate(string filePath)
{
System.Drawing.Image myImage = Image.FromFile(filePath);
System.Drawing.Imaging.PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = new System.Text.RegularExpressions.Regex(":").Replace(System.Text.Encoding.UTF8.GetString(propItem.Value), "-", 2);
return System.DateTime.Parse(dateTaken);
}
Change the .ParseExact line to the following
DateTime dateCreated = DateTime.ParseExact( ConvertToString(dateTakenProperty)**.Substring(0, 19)**, "yyyy:MM:dd HH:mm:ss", provider )
At the end of the string there is probably a null character which can't be processed. Doing a .SubString for the expected length will fix it.

Categories