I created a datatable from an excel sheet. I ran some linq queries and populated the needed columns in a new worksheet. I need help filling in the rows based on the date column. It needs to be dynamic because dates change and IDs could change.
I have an excel sheet that has data like this
L ID | Date | Other | Columns |
D123 1/24/2018
D456 1/25/2018
D678 1/26/2018
D910 1/25/2018
I am trying to create output that looks like this.
L ID 1/24/2018 1/25/2018 1/26/2018
D123 1
D456 1
D678 1
D910 1
I did some code that selected the data needed and then populated the date columns and the ID column in an excel worksheet.
public List<DateTime?> GetTurnOverDates(System.Data.DataTable dt3)
{
List<DateTime?> TurnOverDateList = dt3.AsEnumerable().Select(r => r.Field<DateTime?>("Turnover")).Distinct().OrderBy(x => x).Where(x => x >= DateTime.Today.AddDays(-1)).ToList();
return TurnOverDateList;
public List<String> GetLIDList(System.Data.DataTable dt3, List<DateTime?> list)
{
List<String> LIDList = dt3.AsEnumerable().Where(r => list.Contains(r.Field<DateTime?>("Turnover"))).Select(r => r.Field<String>("LID")).ToList();
return LidList;
}
public void CreateTurnoverWS(String Path, List<DateTime?> DateList, List<String> LidList)
{
int rw = 0;
int c1 = 0;
Excel.Application xlsApp;
Excel.Workbook xlsWorkbook;
Excel.Range range;
xlsApp = new Excel.Application();
xlsWorkbook = xlsApp.Workbooks.Open(Path);
Excel.Sheets xlsworksheets = xlsWorkbook.Worksheets;
var xlsNewSheet = (Excel.Worksheet)xlsworksheets.Add(xlsworksheets[1], Type.Missing, Type.Missing, Type.Missing);
xlsNewSheet.Name = "Turnover";
xlsNewSheet.Cells[1, 3] = "L ID";
xlsNewSheet = (Excel.Worksheet)xlsWorkbook.Worksheets.get_Item(1);
xlsNewSheet.Select();
range = xlsNewSheet.UsedRange;
rw = range.Rows.Count;
c1 = range.Columns.Count;
for (int cCnt = 1; cCnt < DateList.Count(); cCnt++)
{
xlsNewSheet.Cells[1, c1++] = DateList[cCnt];
}
for (int ccnt2 = 0; ccnt2 < LidList.Count(); ccnt2++)
{
xlsNewSheet.Cells[rw++, 3] = LidList[ccnt2];
}
xlsWorkbook.Save();
xlsWorkbook.Close();
}
}
So I basically have this so far in the excel sheet.
L ID 1/24/2018 1/25/2018 1/26/2018
D123
D456
D678
D910
I was researching pivot tables but I am not sure if it will work. I have data going from excel to a datatable, selecting certain data then putting it into a new worksheet. Please advise. Thanks.
For „pivot“-ing have a look at Is it possible to Pivot data using LINQ?
PS: For accessing excel files from code I usually use epplus
Related
I'm trying to add row to a list object from excel file with empty cells. for some reason getting reference object is not set to instance return null. not sure what could be possible solution for this.
ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheet1"];
var rowcount = worksheet.Dimension.Rows;
for(int row = 2; row <= rowcount; row++)
{
list.Add(new Insured
{
item1 = worksheet.Cells [row, 1].Value.ToString().ToLower().Trim(),
item2 = worksheet.Cells [row, 2].Value.ToString().ToLower().Trim(), //<cell is empty
});
}
I need to add the column names within a sheet to a combobox
I have tried the following
var pck = new OfficeOpenXml.ExcelPackage();
pck.Load(new System.IO.FileInfo("test.xlsx").OpenRead());
var ws = pck.Workbook.Worksheets[1];
int totalCols = ws.Dimension.End.Column;
for (int i = 1; i <= totalCols; i++)
{
comboBox1.Items.Add( (ws.Column(i).ToString()));
}
}
But this produces a Null Reference Exception.
Why is that happening?
Ensure that you're loading the package correctly and selecting the values correctly:
// Select workbook
var fileInfo = new FileInfo(#"yourfile.xlsx");
// Load workbook
using (var package = new ExcelPackage(fileInfo)) {
// Itterate through workbook sheets
foreach (var sheet in package.Workbook.Worksheets){
// Itterate through each column until final column
for (int i = 1; i <= sheet.Dimension.End.Column; i++) {
comboBox1.Items.Add(sheet.Cells[1, i].Text);
}
}
}
This runs correctly in a new workbook with two sheets and values in the columns of each sheet.
I finished main things in app I'm doing, but now I want know am I able to check cells type,font,size and border using C# while I'm iterating trough the cells, so when I "copy" values to another Excel document I can use those parameters on the cell that im placing value in?
This is how I read/write from one Excel to another:
Microsoft.Office.Interop.Excel.Application polazniExcel = new
Microsoft.Office.Interop.Excel.Application();
polazniExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook polazna =
polazniExcel.Workbooks.Open(textBoxPolazna.Text.ToString());
Excel.Worksheet Polazni = polazniExcel.Sheets[1];//sheet koji treba unijeti
Microsoft.Office.Interop.Excel.Application krajnjiExcel = new
Microsoft.Office.Interop.Excel.Application();
krajnjiExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook krajnja =
krajnjiExcel.Workbooks.Open(textBoxKrajnja.Text.ToString());
Excel.Worksheet Krajnji_PoMT = krajnjiExcel.Sheets["Po mjestu troška"];//sheet po mjestu troska
Excel.Worksheet Krajnji_Ukupno = krajnjiExcel.Sheets["Ukupno po mjesecima"];//sheet ukupno
Excel.Range brojRedovaPolazni = Polazni.UsedRange;
int brojacRedovaPolazni = brojRedovaPolazni.Rows.Count; //broj redova u polaznom excelu
Excel.Range brojRedovaKrajnjiMT = Krajnji_PoMT.UsedRange;
int brojacRedovaKrajnjiMT = brojRedovaKrajnjiMT.Rows.Count;//broj redova u krajnjem excelu sheet mjesto troska
Excel.Range brojRedovaKrajnjiUkupno = Krajnji_Ukupno.UsedRange;
int brojacRedovaKrajnjiUkupno = brojRedovaKrajnjiUkupno.Rows.Count;//broj redova u krajnjem excelu sheet ukupno
for (int x = 1; x <= brojacRedovaKrajnjiMT - 12; x++)
{
string cellValue = "";
object rangeObject = Polazni.Cells[x+12, kolumna];
Excel.Range xx = (Excel.Range)rangeObject;
object rangeValue = xx.Value2;
if(rangeValue!=null)
{
cellValue= rangeValue.ToString();
}else
{
cellValue = null;
}
Krajnji_PoMT.Cells[(x + 12), kolumna_broj].Value2 = cellValue;
}
brojacRedovaKrajnjiMT - 12 because 1st 12 rows are just a title, and "kolumna" represents number of column inside that sheet.
I am using Microsoft.Office.Interop.Excel for writing data to excel
Now I'm using below code to fill data to a range of cells. Let's say from P10 to P20
Excel.Worksheet ps_sheet = //current worksheet
string[,] data = new string[11,1];
var r = ps_sheet.Range["P10", "P20"];
r.Value2 = data;
The above code is working properly, but if there's only one cell in the range (e.g. "P20" to "P20") the code won't work, the cell is showing the old data.
Excel.Worksheet ps_sheet = //current worksheet
string[,] data = new string[1,1];
var r = ps_sheet.Range["P20", "P20"];
r.Value2 = data;
The excel.range can have one cell only or have multiple cells, since I'm doing a loop.
Is there any reason why this situation happens and how to fix?
Use only one parameter, second parameter is optional
var r = ps_sheet.Range["P20"];
Worksheet.Range Property
I changed to below code and it works:
if (data.GetLength(0) == 1)
{
r = ps_sheet.Range["P10"];
r.Value2 = data[0, 1];
}
else
{
r = ps_sheet.Range["P10", "P20"];
r.Value2 = data;
}
I specially made a case if the data has only one row...
Don't know if there're any better ways to achieve this
I have an Excel file with a cell that has set "Data Validation" to "List". Thanks to that, this cell is a drop down list. How can I read the elements of this list using C# Excel Interop? I can easily read the currently selected value:
Range range = xlWorkSheet.UsedRange; // Worksheet
string cellValue = (range.Cells[x, y] as Excel.Range).Value2.ToString();
but I cannot read the content of the dropdown list that this cell contains.
As it was stated here How do I read the values of Excel dropdowns or checkboxes from c# or vb.net? there is no easy way to do that, but it is possible to create custom function and do it manually. Below is my function that that reads drop down values into a string list. This function is based on an a question mentioned before, but I added support for formulas on other sheets.
List<string> ReadDropDownValues(Excel.Workbook xlWorkBook, Excel.Range dropDownCell)
{
List<string> result = new List<string>();
string formulaRange = dropDownCell.Validation.Formula1;
string[] formulaRangeWorkSheetAndCells = formulaRange.Substring(1, formulaRange.Length - 1).Split('!');
string[] splitFormulaRange = formulaRangeWorkSheetAndCells[1].Split(':');
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(formulaRangeWorkSheetAndCells[0]);
Excel.Range valRange = (Excel.Range)xlWorkSheet.get_Range(splitFormulaRange[0], splitFormulaRange[1]);
for (int nRows = 1; nRows <= valRange.Rows.Count; nRows++)
{
for (int nCols = 1; nCols <= valRange.Columns.Count; nCols++)
{
Excel.Range aCell = (Excel.Range)valRange.Cells[nRows, nCols];
if (aCell.Value2 != null)
{
result.Add(aCell.Value2.ToString());
}
}
}
return result;
}