I am fetching the value present in the excel cell which is a date like 20-3-2004 using the following code:
string logResult = null;
string ResultFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + ResultFile;
Microsoft.Office.Interop.Excel.Application myapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = myapp.Workbooks.Open(ResultFilePath);
Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.get_Item(1);
var cell = (Microsoft.Office.Interop.Excel.Range)sheet.Cells[row, col];
logResult = cell.Value.ToString();
but in the logresult I am always getting date in format 20/3/2004 . please suggest how get the exact format of the date which is written in the cell.
A date value has no format. It is the code that you use to display it that present that value is some form on video.
In your case, it is the ToString() call that trasform whatever has been read on the cell in a string. If it is a date then it trasform it according to the current international settings of your machine.
You could force the ToString() method to use a particular format applying a Format Mask parameter like
logResult = cell.Value.ToString("d-M-yyyy");
See the topic on MSDN about DateTime.ToString()
Related
I want to do a date comparison to check whether is the Before Period is bigger than After Periode
So far it has been working properly until the date range is a bit tricky
For example
The value is from a dropdownlist item
Before period is 21-10-2022
After period is 04-11-2022
It will trigger the error message I set if the before period is bigger than the period after
I have a code like this
If CDate(ddlPeriodeBefore.SelectedValue) <= CDate(ddlPeriodeBefore.SelectedValue) Then
'Does the job if the the before period is smaller than after period
Else
lblInfo.Text = "Period BEFORE Must Be SMALLER Than Period AFTER."
End If
Can anyone help me? it keeps saying "conversion from string to date is not valid"
I've tried datetime.parse, parse exact, cdate, convert.todatetime but nothing works so far, or maybe I used it the wrong way
Please help, thanks in advance
Tim Schmelter's suggestion is not wrong, but I did want to provide an alternative. Create a collection of Tuple, add the dates (both formatted string and native value) to the collection, then bind the control to the list.
Here is the alternative:
Dim dates As New List(Of Tuple(Of String, DateTime))()
Dim today = DateTime.Today
For daysSubtract = 90 To 0 Step -1
Dim dateToAdd = today.AddDays(-daysSubtract)
dates.Add(New Tuple(Of String, DateTime)(dateToAdd.ToString("dd-MM-yyyy"), dateToAdd))
Next
ddlPeriodeBefore.ValueMember = "Item1"
ddlPeriodeBefore.DisplayMember = "Item2"
ddlPeriodeBefore.DataSource = dates
ddlPeriodeAfter.ValueMember = "Item1"
ddlPeriodeAfter.DisplayMember = "Item2"
ddlPeriodeAfter.DataSource = dates
Now when you go to get the selected value, you can use a simpler conversion since the stored object is already a DateTime:
Dim beforePeriod = DirectCast(ddlPeriodeBefore.SelectedValue, DateTime)
Dim afterPeriod = DirectCast(ddlPeriodeAfter.SelectedValue, DateTime)
If (beforePeriod <= afterPeriod) Then
' ...
Else
lblInfo.Text = "Period BEFORE Must Be SMALLER Than Period AFTER."
End If
The advantage to this approach is that you do not have to refactor your code if the date formatting changes.
If DateTime.Parse works depends on your curren culture because you don't pass any. For me this works fine (but for you not):
Dim selectedValue1 = "21-10-2022"
Dim selectedValue2 = "04-11-2022"
Dim beforePeriod = Date.Parse(selectedValue1)
Dim afterPeriod = Date.Parse(selectedValue2)
So either you know the correct culture that you have used when you have created this string, then you can pass this as second parameter to Date.Parse, or you use ParseExact:
Dim beforePeriod = Date.ParseExact(selectedValue1, "dd-MM-yyyy", CultureInfo.InvariantCulture)
Dim afterPeriod = Date.ParseExact(selectedValue2, "dd-MM-yyyy", CultureInfo.InvariantCulture)
The culture is relevant because they can have different date separators and the order of the day-, month- and year-tokens are different.
Selenium is incorrectly reading the date as 43095 when I enter 26-12-2017. How to get Selenium to read the correct date?
for (int i=0;i<=TcRow;i++)
{
for (int j=0;j<TcCol;j++)
{
Cell Cell=TcSheet.getRow(i).getCell(j);
}
}
Am I reading the format incorrectly?
TcSheet.getRow(i).getCell(j).setCellType(Cell.CELL_TYPE_STRING);
What changes do I need to do here to make sure they read both the string and the date field?
data[i][j]=TcSheet.getRow(i).getCell(j).getStringCellValue();
}
I also faced the same issue during reading the excel file where I'm fetching date is formatted in dd/mm/yyyy format and selenium fetching wrong value.
For that, I have used DataFormatter. It will returns Excel cell value with format e.g. Date format 15-04-208 in excellent then it will returns date with same format. Look below code that I used in my Framework. Hope it will also work for you.
FileInputStream fis = new FileInputStream("path\\to\\file.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(worksheet);
DataFormatter formatter = new DataFormatter();
Cell cell = sheet.getRow(rowNum).getCell(cellNum);
String cellValue = formatter.formatCellValue(cell);
System.out.println(cellValue);
return cellValue;
Let me know if you have any query.
I'm having trouble with Excel's custom format using EPPLUS. Here's my code:
var destFile = new FileInfo(#"C:\temp\test1.xlsx");
var fileName = "test1";
using (ExcelPackage pck = new ExcelPackage(destFile))
{
pck.Workbook.Worksheets.Add(fileName); // Create the worksheet in package
pck.Workbook.Worksheets[fileName].Cells["A2"].Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
pck.Workbook.Worksheets[fileName].Cells["A2"].Style.Numberformat.Format = "d-mmm-yy";
pck.Save();
}
I'm getting the following:
The custom format is showed right, but the value in the cell doesn't display the format needed. Here's what I'm trying to get:
Note: I need the full date value DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss") for other files, but the custom format is all I need for this file.
What do I need to change to get this to work?
Thanks to #PaullAbbott, here's the correct answer:
pck.Workbook.Worksheets[fileName].Cells["A2"].Value = DateTime.Now;
This displays the results that I needed.
I've got this code to apply a "header" (big, top-of-the-sheet "title") to a sheet:
// Initialize
private static SLDocument sl;
. . .
sl = new SLDocument();
// Create a Style
SLStyle styleHeading = sl.CreateStyle();
styleHeading.SetFont(FontSchemeValues.Major, 36);
styleHeading.Font.Italic = true;
styleHeading.Font.FontName = "Candara";
// Create a Defined Name (Range) and give it a value and style
sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13");
sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
sl.SetCellStyle("UnitName", styleHeading);
// Save the sheet
string appDataFolder = HttpContext.Current.Server.MapPath("~/App_Data/");
string spreadsheetLightFilename = "PlatypiTest.xlsx";
string fullspreadsheetLightPath = Path.Combine(appDataFolder, spreadsheetLightFilename);
sl.SaveAs(fullspreadsheetLightPath);
Note: I verified that "Sheet1" was right with this code:
var nameList = sl.GetSheetNames();
string s = nameList[0]; // "s" is "Sheet1"
The file is created and saved, but it is devoid of content; when I open it, cell A1 is highlighted, but is content-free.
Am I missing a vital step, or going about this completely wrong?
What are you doing is logically fine.
This line
sl.SetDefinedName("UnitName", "Sheet1!$A$1:$A$13");
indeed creates a named range. You can see it if you open the resulting file in Excel and look at the cell selector:
or the Name Manager:
The problem is though that Spreadsheet Light has a very basic support for Defined names - basically all you can do is to create a name and use it inside the formulas. All methods that manipulate content expect single cell reference. Btw, all these methods do not throw exception if you don't pass a valid cell reference, but return bool indicating success/failure.
For instance, if you change your code to
bool success1 = sl.SetCellValue("UnitName", "Pennsylvania Platypi Presumptuously Parasailing");
bool success2 = sl.SetCellStyle("UnitName", styleHeading);
you will see that both success variables are false.
Shortly, if you want to bring some content to the Excel file, you should do it cell by cell. It even does not support regular (unnamed) ranges.
Theoretically, at least, you could do it this way:
// from http://stackoverflow.com/questions/36481802/what-is-the-analogue-to-excel-interops-worksheet-usedrange-rows-in-spreadsheet
var stats = sl.GetWorksheetStatistics();
var rowcount = stats.NumberOfRows;
SLStyle entireSheetRangeStyle = sl.CreateStyle();
entireSheetRangeStyle.// (set style vals)
. . .
sl.SetRowStyle(1, rowcount, entireSheetRangeStyle);
I need to store numeric in number category (right click->Catergory=number). I have tried using the below code, but it saves in general format.
String valueAsString = "2345";
HSSFCell cellE1 = row1.createCell((short) 4);
cellE1.setCellValue(new BigDecimal(valueAsString).doubleValue());
You need to set a cell style to the cell, which formats it as you want. Something like
Worbook wb = new HSSFWorkbook();
DataFormat fmts = wb.getCreationHelper().createDataFormat();
// Cell Styles apply to the whole workbook, only create once
CellStyle numericStyle = wb.createCellStyle();
numericStyle.setDataFormat(fmts.getFormat("0")); // Format string
....
// Apply to the cells
Row r = sheet.createRow(0);
Cell c = r.createCell(0); // A1
c.setCellStyle(numericStyle);
c.setCellValue(Double.parseDouble("12345"));