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.
Related
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've encountered a problem. I'm trying to read data from xlsx document using LinqToExcel. The data is retrieved but the document has cells which are interpreted as formulas with text like "=- Something". Is it possible to get those cells text and not the counted value of the formula?
var book = new LinqToExcel.ExcelQueryFactory(path);
var worksheetNames = book.GetWorksheetNames();
var query =
from row in book.WorksheetNoHeader()
where row[0] != ""
select row;
With LinqToExcel you can't receive formula, because linqtoExcel uses OleDB to access sheet. OleDB doesn't allow to access formulas. Instead linqtoExcel you can use Worksheet.Range Property
Example:
Range range = (Range)sheet.Cells[i, j];
return range.Formula;
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;
}
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.
I have an openFileDialog tool. I will choose a excel file from my computer and my programme read a column (for example A column) and write my listbox on GUI. How can i do it via OleDB? I am new at C#. If you explain detailed, I will be happy for that.
Thank you for your help.
In order to use the OLEDB provider successfully we have to consider a few points.
The OLEDB provider for Excel 2003 files is different from the one used for
Excel 2007/2010 files. So, the first thing we have to do
is determining the Excel file format in order to select the correct provider.
In the code example below I simply check the extension of the file to determine
the Excel file format. Please note, that there are more elaborated methods to
determine the Excel file format (e.g. via the magic bytes).
To select all rows of a Excel sheet we need to know the name of
the Excel sheet. The standard sheet names are language dependent and
could be renamed by the user.
So, we need a way to determine the name of the sheets included
in a Excel file to be language independent (and of course independent of renamed sheets).
Fortunately, the OleDbConnection class provides
a method called GetOleDbSchemaTable which allows us to get all
the sheet names in an Excel file.
The OLEDB provider for Excel
supports an extended property called HDR. Setting HDR to Yes
means that the first row of a sheet contains the column titles.
So, if you use column titles you should set
HDR=Yes.
So, to summarize the code sample below does the following (on button click):
Determines the Excel file type based on the file extension.
Selects the correct OLEDB provider based on the excel file type to build the connection string.
Determines the sheet names included in the Excel file.
Selects the first sheet, selects all rows and stores the rows in a DataTable called mytable.
Displays all values of the first column in a listbox called listbox1.
Code sample:
private static bool IsExcelXmlFileFormat(string fileName)
{
return fileName.EndsWith("xlsx", StringComparison.OrdinalIgnoreCase);
}
private void button1_Click(object sender, EventArgs e)
{
// Open your FileOpenDialog and let the user select a file...
string fileName = "c:\\temp\\myexcelfile.xlsx";
OleDbConnectionStringBuilder connStringBuilder =
new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = fileName;
if (IsExcelXmlFileFormat(fileName))
{
// Set HDR=Yes if first row contains column titles.
connStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;");
}
else
{
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;");
}
DataSet data = new DataSet();
using (OleDbConnection dbConn = new OleDbConnection(connStringBuilder.ConnectionString))
{
dbConn.Open();
DataTable sheets = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
using (OleDbCommand selectCmd = new OleDbCommand(
String.Format("SELECT * FROM [{0}]", sheets.Rows[0]["TABLE_NAME"]), dbConn))
{
using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter())
{
dbAdapter.SelectCommand = selectCmd;
dbAdapter.Fill(data, "mytable");
}
}
}
// To enumerate all rows use the following code.
// foreach (DataRow row in data.Tables["mytable"].Rows)
// {
// Console.Out.WriteLine(row[0]);
// }
// Display the values of column 0 in a listbox called listBox1.
listBox1.ValueMember = data.Tables["mytable"].Columns[0].ColumnName;
listBox1.DisplayMember = data.Tables["mytable"].Columns[0].ColumnName;
listBox1.DataSource = data.Tables["mytable"];
}