EPPlus get excel row and columns count - c#

I have an excel file which has say 5 columns and 5 rows.
I am using EPPlus (.net core c#)to parse the contents of the file.
I have the below code to count the rows and columns and then parse contents of this excel file.
using (ExcelPackage package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
//Parse here
}
}
}
With 5 rows and 5 columns of data as mentioned this works fine.
If I update and save the same file, and delete say 3 rows and 3 columns.
Now if I read this file again it still shows 5 columns and rows. Not sure if there is another way to read actual rows and columns?
Am I missing something here.

Try this
using (ExcelPackage package = new ExcelPackage(stream))
{
string directoryServerPath = // your file saving path in server;
if (!Directory.Exists(directoryServerPath))
Directory.CreateDirectory(directoryServerPath);
System.IO.DirectoryInfo directoryFiles = new DirectoryInfo(directoryServerPath);
foreach (FileInfo file in directoryFiles.GetFiles())
{
file.IsReadOnly = false;
file.Delete();
}
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
//Parse here
}
}
package.SaveAs(new System.IO.FileInfo(directoryServerPath + fileName));
System.IO.File.SetAttributes(directoryServerPath + fileName, FileAttributes.ReadOnly);
}

Related

EPPlus: Find if the entire row is empty in Excel

I am using EPPlus library in my .net core web api. In the said method I want to validate he uploaded excel. I want to find out if my entire row is empty. I have the following code:
using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
//loop through rows and columns
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= ColCount; col++)
{
var rowValue = worksheet.Cells[row, col].Value;
//Want to find here if the entire row is empty
}
}
}
rowValue above would give me if the particular cell if empty or not. Is it possible to check for the entire row and proceed to next row if empty.
you can check the row cell range value with linq:
var startRow = 1;
var endRow = 1;
var columnStart = 1;
var columnEnd = worksheet.Cells.End.Column;
var cellRange = worksheet.Cells[startRow, columnStart , endRow, columnEnd];
var isRowEmpty = cellRange.All(c => c.Value == null)
If you do not know the number of columns to check you can take advantage of the fact that the Worksheet.Cells collection only contains entries for cells that actually have values:
[TestMethod]
public void EmptyRowsTest()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[] { new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(object)) });
//Only fille every other row
for (var i = 0; i < 10; i++)
{
var row = datatable.NewRow();
if (i % 2 > 0)
{
row[0] = i;
row[1] = i * 10;
row[2] = Path.GetRandomFileName();
}
datatable.Rows.Add(row);
}
//Create a test file
var existingFile = new FileInfo(#"c:\temp\EmptyRowsTest.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var pck = new ExcelPackage(existingFile))
{
var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
pck.Save();
}
//Load from file
using (var pck = new ExcelPackage(existingFile))
{
var worksheet = pck.Workbook.Worksheets["Sheet1"];
//Cells only contains references to cells with actual data
var cells = worksheet.Cells;
var rowIndicies = cells
.Select(c => c.Start.Row)
.Distinct()
.ToList();
//Skip the header row which was added by LoadFromDataTable
for (var i = 1; i <= 10; i++)
Console.WriteLine($"Row {i} is empty: {rowIndicies.Contains(i)}");
}
}
Gives this in the output (Row 0 is the column headers):
Row 1 is empty: True
Row 2 is empty: False
Row 3 is empty: True
Row 4 is empty: False
Row 5 is empty: True
Row 6 is empty: False
Row 7 is empty: True
Row 8 is empty: False
Row 9 is empty: True
Row 10 is empty: False
You can set a bool in the for loop at row level. Then loop all the cells and change the bool when a cell is not empty.
//loop through rows and columns
for (int row = 1; row <= rowCount; row++)
{
//create a bool
bool RowIsEmpty = true;
for (int col = 1; col <= colCount; col++)
{
//check if the cell is empty or not
if (worksheet.Cells[row, col].Value != null)
{
RowIsEmpty = false;
}
}
//display result
if (RowIsEmpty)
{
Label1.Text += "Row " + row + " is empty.<br>";
}
}
You can use the worksheet.Cells[row, col].count() method for this.
If the row is empty then this method will return 0.

Issue select statement on excel sheet without using OLEDB provider

How can I use a select statement on an Excel sheet without using any oledb Provider? This is what I got so far by using using Excel = Microsoft.Office.Interop.Excel;. Iterating through each cell using a nested for-loop feels wrong...
// Create excel application object by calling constructor
Excel.Application xlApp = new Excel.Application();
// Open excel file using excel object
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"D:\Temp\file.xls");
// Open first sheet within excel document (index start at 1, not 0)
Excel._Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets["SheetName"];
// Get used sheet bounderies
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get row count
int rowCount = xlRange.Rows.Count;
// Get column count
int colCount = xlRange.Columns.Count;
//iterate over the rows and columns and print to the console as it appears in the file
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console if cell value ends on 'd'
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null && (xlRange.Cells[i, j].Value2.ToString()).EndsWith("d"))
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
While you could use the items interface to a range to go over all the cells, you are outputting for each row and conditionally outputting across columns, for is the right approach.
However, you could tighten the code up a little:
var rowCount = xlRange.Rows.Count;
var colCount = xlRange.Columns.Count;
for (int row = 1; row <= rowCount; ++row) {
Console.WriteLine();
for (int col = 1; col <= colCount; ++col) {
//write the value to the console if cell value ends on 'd'
if (xlRange.Cells[row, col]?.Value2?.ToString().EndsWith("d") ?? false)
Console.Write(xlRange.Cells[row, col].Value2.ToString() + "\t");
}
}

Populating a listbox in c#

I have a listbox and I manage to bind the Excel worksheet to the list box (after hours of researching on the Internet).
Now I need to read the values from the sheet into the listbox, but unable to locate any suitable solution.
This is what I have done so far:-
private void LoadExcelSheet(string path, int sheet){
_Application excel = new Excel.Application();
Workbook wb;
Worksheet ws;
int row = 0;
int col = 0;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
for (row = 1; row < 10; row++){
for (col = 1; col < 6; col++){
listBox1.Items.Add(ws.Cells[row, col].Value2);
}
}
}
//------------------ end of LoadExcelSheet---------------------------
this only display 1 row with each item of data on top of each other eg:-
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
instead of: aaaaaaaa bbbbbbbb cccccccc dddddddd
Thanks in advance..
The issue is with your for loops, try this:
for (var row = 1; row < 10; row++)
{
string r = "";
for (var col = 1; col < 6; col++)
{
r += " " + ws.Cells[row, col].Value2;
}
listBox1.Items.Add(r.Trim());
}
You are populating the list box inside a loop containing the columns, try something like
for (row = 1; row < 10; row++){
string a = "";
for (col = 1; col < 6; col++){
a += ws.Cells[row, col].Value2+" ";
}
listBox1.Items.Add(a);
}
Let's split the problem
Data collection
Collected data representation
Data collection (with a help of Linq):
using System.Linq;
...
string[] data = Enumerable
.Range(1, 9) // 9 rows, starting from 1
.Select(row => string.Join(" ", Enumerable // cols are joined with space
.Range(1, 5) // 5 columns in each row
.Select(col => ws.Cells[row, col].Value2)))
.ToArray();
And data representation (as ListBox items):
listBox1.Items.AddRange(data);

Read xlsx file on C#.net

I want to read xlsx elements and print them 4 by 4 till all element are printed but i have a problem because it prints me all elements of the file. Any idea how to print them 4 by 4
// Open the Excel file.
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath(#"C:\Users\user\Documents\Book2.xlsx"));
// Get the first worksheet.
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
// Get the range of cells which has data.
Excel.Range xlRange = xlWorksheet.UsedRange;
// Get an object array of all of the cells in the worksheet with their values.
object[,] valueArray = (object[,])xlRange.get_Value(
Excel.XlRangeValueDataType.xlRangeValueDefault);
for (int row = 1; row <= xlWorksheet.UsedRange.Rows.Count; ++row)
{
for (int col = 1; col <= xlWorksheet.UsedRange.Columns.Count; ++col)
{
Console.WriteLine(valueArray[row, col].ToString());
}
int y = xlWorksheet.UsedRange.Rows.Count / 4;
for() {
Console.WriteLine("4 addresat e para u printuan");
Console.WriteLine(" ");
}
}
Don't loop until you get to the end of columns/tows collection. Loop 1 through 4 (or 0 to 3)...
for (int row = 1; row <= 4; ++row)
{
for (int col = 1; col <= x4; ++col)
{
Console.WriteLine(valueArray[row, col].ToString());
}
}

How to write a text file from a .NET DataGridView control cell values?

I have the following code that should loop through all the rows in my DataGridView, and write all their cell values to a text file.
However, it outputs all the rows, but only the first cell of each one, and not the other three cells.
string file_name = "C:\\test1.txt";
var objWriter = new System.IO.StreamWriter(file_name);
int count = dgv.Rows.Count;
for (int row = 0; row < count; row++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[0].Value.ToString());
}
objWriter.Close();
for (int row = 0; row < count; row++)
{
int colCount = dgv.Rows[row].Cells.Count;
for ( int col = 0; col < colCount; col++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
}
// record seperator could be written here.
}
Although, it would be cleaner if you used a foreach loop.
TextWriter sw = new StreamWriter(#"D:\\file11.txt");
int rowcount = dataGridViewX1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dataGridViewX1.Rows[i].Cells[0].Value.ToString());
}
sw.Close();
MessageBox.Show("Text file was created." );

Categories

Resources