How to get rid of empty cells in EPPlus - c#

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
});
}

Related

ClosedXml Excel Add multiple values to Rows

Trying to add values from an array string[] to a row in Excel.
When I'm trying to use dt.Rows.Add(string[i]) it is added to the Excel sheet. The problem is it is added vertically, which is quite obvious because I'm only adding one item to the row and then insert a new row. My question now is how to add every item from the string[] to one row so that my data is displayed horizontally.
For example string[] values = {"a","b","c","d"};
The output I have at the moment:
a
b
c
d
The output I want:
a b c d (each in a different cell).
A1 = a
B1 = b
...
I've already been able to add columns to the worksheet, I only need my data to be right.
This is my code for now.
//Add columns
dt.Columns.AddRange(columns.Select(c => new DataColumn(c.ToString())).ToArray());
List<string> temp;
string[] values;
for (int i = 0; i < 7; i++)
{
temp = new List<string>();
temp.Add(timeStamps[i].ToString());
foreach (var item in tagCollection)
{
if (timeStamps[i].Date == item.time)
{
temp.Add(item.min);
temp.Add(item.max);
temp.Add(item.avg);
}
}
int index = 0;
values = new string[temp.Count];
foreach (var item in temp)
{
values[index] = item;
dt.Rows.Add(values[index]);
index++;
}
}
//Convert datatable to dataset and add it to the workbook as worksheet
ds.Tables.Add(dt);
workbook.Worksheets.Add(ds);
The solution may go through the following:
string[] cars = { "Volvo", "BMW", "Mazda" };
table.Rows.Add(cars[0].ToString(), cars[1].ToString(), cars[2].ToString());
Output:
Just need to adapt to your own code.
You've to guarantee that your Datasheet has the columns needed to display all data in the same row. If you didn't do that, for sure it will generate a matrix error.
This works for me. I Changed the foreach loop and discoverd that there was a NewRow() method.
int index = 0;
values = new string[temp.Count];
DataRow newRow;
newRow = dt.NewRow();
foreach (var item in temp) {
values[index] = item;
newRow.ItemArray = temp.Cast<object>().ToArray();
index++;
}
dt.Rows.Add(newRow);

Filter specific rows of worksheet C#

I'm currently trying to get specific rows of an Excel file in my code.
I get the data of my Excel file with this code:
FileInfo existingFile = new FileInfo(local_in_file_path);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
List<string> testlist = new List<string>();
List<string> articlelist = new List<string>();
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
testlist.Add(worksheet.Cells[row, col].Value?.ToString().Trim());
foreach (var i in testlist)
{
if (articlelist.Contains(i))
{
continue;
}
else
{
articlelist.Add(i);
}
}
}
}
foreach (var article in articlelist)
{
var rows = worksheet.Row().Where(n => n = article); //doesnt work
}
In the foreach loop I want all rows, in which the specific article occurs. How can I do this?
Be careful because when you add something to testlist you are picking only 1 cell everytime (so if your excel file is structured like "1 row has 'article name' , 'description' ecc you are running through every col in every row so it's pretty inefficient, if you could only provide an example of your excel file we can try to help, and does that foreach create an exception or something else?

Need assistance inserting certain data from datatable to Excel dynamically C#

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

Iterating and adding all column names to a ComboBox using EPPlus

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.

Office Open XML - Target Cell by its content

How to target Cell if I know its content (there are no duplicates in the xlsx document) using Office Open XML?
I mean I have xlsx sheet (template) and somewhere in it placed my "variable". For example "<<_time>>". I want to find that element (by "variable" name) and change the cell value (current time in this case).
Basic code:
FileInfo newFile = new FileInfo(#"...");
FileInfo template = new FileInfo(#"...");
using (ExcelPackage xlPackage = new ExcelPackage(newFile, template))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.First();
//need target Cell by it's value (must use for-loop?)
//worksheet.Cells[...].Value = "...";
xlPackage.Save();
}
Ok, I solved it by classic loop.
var start = worksheet.Dimension.Start;
var end = worksheet.Dimension.End;
for (int row = start.Row; row <= end.Row; row++)
{
for (int col = start.Column; col <= end.Column; col++)
{
string cellValue = worksheet.Cells[row, col].Text.ToString();
if (cellValue == "<<_time>>")
{
worksheet.Cells[row, col].Value = "..";
}
}
}

Categories