Query Excel where Rows and Columns are reversed - c#

How can I query an Excel file where the rows and columns are reversed / rotated 90 degrees?
Can it be done with a SELECT query, or do I need to recurse the cells programmatically?
It's for a .NET app, so linq or other suggestions are welcome.

Transpose a Datatable with a code like this:
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable(inputTable.TableName);
outputTable.Columns.Add(inputTable.Columns[0].ColumnName);
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
newRow[0] = inputTable.Columns[rCount].ColumnName;
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}

.NET does not include a method to transpose data tables. You have to make your own. This website Link has a tutorial on an example transpose method. I will copy and paste the code snippet below:
private DataTable Transpose(DataTable dt)
{
DataTable dtNew = new DataTable();
//adding columns
for(int i=0; i<=dt.Rows.Count; i++)
{
dtNew.Columns.Add(i.ToString());
}
//Changing Column Captions:
dtNew.Columns[0].ColumnName = " ";
for(int i=0; i<dt.Rows.Count; i++)
{
//For dateTime columns use like below
dtNew.Columns[i+1].ColumnName =Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
//Else just assign the ItermArry[0] to the columnName prooperty
}
//Adding Row Data
for(int k=1; k<dt.Columns.Count; k++)
{
DataRow r = dtNew.NewRow();
r[0] = dt.Columns[k].ToString();
for(int j=1; j<=dt.Rows.Count; j++)
r[j] = dt.Rows[j-1][k];
dtNew.Rows.Add(r);
}
return dtNew;
}

Related

not to read empty or null records in datatble from text file - c#

I have a function which reads all the tab delimited records from a text file into a datatble, but I have a lot empty or null columns also which are tab delimited. I just want to read all records where column 3 is not null or non empty. how can I do it?
Here is my simple method
public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
int i = 0;
foreach (string line in lines)
{
var cols = line.Split('\t');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
i++;
}
return tbl;
}
The simplest would be to insert a check for IsNullOrWhiteSpace for column 3 before creating and and adding values to the datatable like:
public DataTable ConvertTextToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
var lines = System.IO.File.ReadLines(filePath);
int i = 0;
foreach (string line in lines)
{
var cols = line.Split('\t');
if (cols.Length > 3 && String.IsNullOrWhiteSpace(cols[3]))
{
continue; //Ignore this line
}
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
i++;
}
return tbl;
}
Also notice the use of var lines = System.IO.File.ReadLines(filePath); instead of File.ReadAllLines, since it will evaluate the file line by line, instead of loading up all the files content in memory.

Is it possible to copy row (with data, merging, style) in Excel using Epplus?

The problem is that I need to insert data into Excel from the collection several times using a single template for the entire collection.
using (var pckg = new ExcelPackage(new FileInfo(association.TemplatePath)))
{
var workSheet = pckg.Workbook.Worksheets[1];
var dataTable = WorksheetToDataTable(workSheet);
/*Some stuff*/
FindAndReplaceValue(workSheet, dictionary, row);
}
private DataTable WorksheetToDataTable(ExcelWorksheet oSheet)
{
int totalRows = oSheet.Dimension.End.Row;
int totalCols = oSheet.Dimension.End.Column;
DataTable dt = new DataTable(oSheet.Name);
DataRow dr = null;
for (int i = 1; i <= totalRows; i++)
{
if (i > 1) dr = dt.Rows.Add();
for (int j = 1; j <= totalCols; j++)
{
if (i == 1)
dt.Columns.Add((oSheet.Cells[i, j].Value ?? "").ToString());
else
dr[j - 1] = (oSheet.Cells[i, j].Value ?? "").ToString();
}
}
return dt;
}
First picture - My template. Second - First element of collection (with data, style, merging). Third - Other elements has only data
I just made copies of rows
for (int i = 0; i < invoiceList.Count; i++)
{
workSheet.Cells[1, 1, totalRows, totalCols].Copy(workSheet.Cells[i * totalRows + 1, 1]);
}
If you want to copy range just use :
workSheet.Cells["A1:I1"].Copy(workSheet.Cells["A4:I4"]);

Show datasource rows as columns on a DataGridView (Winforms)

I wanna show all my DataSource rows on a DataGridView, but not as rows but as columns of a row. Each 12 items retrieved, I wanna insert a new row on the DataGridView and populate this new row with more items from the DataSource (12 at each row).
My DataSource retrieves just one item each, and using it directly with the DataGridView is working nicely, but shown a different row for each item.
Any hints?
Thanks to #SriramSakthivel.
private void AddToList(DataTable dt)
{
possibleWords = 0;
// Cleans the data grid view
WordList.DataSource = null;
WordList.Refresh();
// Let's transform the original data table onto another, changing rows by columns
DataTable table = new DataTable();
for (int i = 0; i < 10; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow r;
int col = 0;
//for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
for (int j = 0; j < dt.Rows.Count; j++)
{
if (col >= 10)
{
table.Rows.Add(r);
col = 0;
r = table.NewRow();
}
r[col++] = (dt.Rows[j][0]).ToString().ToUpper();
possibleWords++;
}
table.Rows.Add(r);
}
// Puts the new data table as datasource of the word list
DataView dv = table.DefaultView;
WordList.DataSource = dv;
if (possibleWords == 0)
return;
WordList.Columns[0].DefaultCellStyle.BackColor = Color.WhiteSmoke;
WordList.ColumnHeadersVisible = false;
WordList.RowHeadersVisible = false;
}

Repost (sort of) -- Invalid Cast AGAIN (DataTable Row Summation)

I have the ability to total each column and add the row -- using this block of code :
DataRow totalRow = t.NewRow();
int colCount = 1;
for (int j = 1; j < t.Columns.Count; j++)
{
if (t.Columns[j].ColumnName == "Client")
{
t.Columns.Cast<DataColumn>().Skip(1);
}
else
{
int colTotal = 0;
for (int i = 1; i < t.Rows.Count; i++)
{
colTotal += Convert.ToInt32(t.Rows[i][j]);
totalRow[t.Columns[j].ColumnName] = colTotal;
}
}
++colCount;
}
t.Rows.Add(totalRow); <br>
**WHY O WHY Can't I just alter this OR use this block (below) to total the rows and insert a new column with the totals of each row??? I don't know why I'm having such a block on this--I'm sure it's relatively simple I just am not seeing it! It is driving me nuts -- I've been at this for 3 days --its sad.
int sum = 0;
foreach (DataRow rows in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
int number = Convert.ToInt32(dt.Rows[j].Field<int>(i));
sum += number;
}
}
rows["testrow"] = sum;
}
dataGridView1.DataSource = dt;
}
The error is still "Specified cast in not valid" -- The datatable is coming from an excel sheet. I can use it on a self-made DataTable just fine. I don't understand.
This block of code works just fine and gives me the sum of the rows in a new column
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("amount1", typeof(int));
dt.Columns.Add("amount2", typeof(int));
dt.Columns.Add("amount3", typeof(int));
dt.Columns.Add("amount4", typeof(int));
dt.Columns.Add("Row Totals", typeof(int));
DataRow dr = dt.NewRow();
dr[0] = 100;
dr[1] = 200;
dr[2] = 300;
dr[3] = 400;
dr[4] = 0;
dt.Rows.Add(dr);
int sum = 0;
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
// int sum = 0;
int number = dt.Rows[j].Field<int>(i);
sum += number;
}
}
It seems likely that it's not an int but a long (or byte) you can cast a long to int but you can't unbox a long to an int which the code in question tries to do.
if that's the case you can do something like
var sum = (from column in dt.Columns.AsEnumerable<DataColum>().Skip(1)
from row in dt.Rows.AsEnumerable<DataRow>().Skip(1)
where column.ColumnName != "Client"
select (long)row[column]).Sum();
Drum roll please ---
Thank you guys for comments and suggestions they did help me get to this point understanding what exactly was going on behind the scenes.
System.Data.DataTable dt = ds.Tables[0];
dt.Columns.Add("testrow", typeof(int));
DataRow dr = dt.NewRow();
int sum = 0;
for (int i = 1; i < dt.Columns.Count; i++)
{
for (int j = 1; j < dt.Rows.Count; j++)
{
if (j == dt.Rows.Count - 1)
{
dt.Rows[i][j] = Convert.ToInt32(sum);
sum = 0;
}
else
{
object number = dt.Rows[i][j];
sum += Convert.ToInt32(number);
}
}
dataGridView1.DataSource = dt;
}

DataGridView with horizontal columns

Is it possible to have a horizontal columns in DataGridView, with ability to bind those columns?
You dont have to Flip the DataGridView instead Flip the DataSet to bind
Try this:
public DataSet FlipDataSet(DataSet my_DataSet)
{
DataSet ds = new DataSet();
foreach (DataTable dt in my_DataSet.Tables)
{
DataTable table = new DataTable();
for (int i = 0; i <= dt.Rows.Count; i++)
{ table.Columns.Add(Convert.ToString(i)); }
DataRow r;
for (int k = 0; k < dt.Columns.Count; k++)
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
{ r[j] = dt.Rows[j - 1][k]; }
table.Rows.Add(r);
}
ds.Tables.Add(table);
}
return ds;
}
For more details visit Displaying-Vertical-Rows-in-DataGrid-View

Categories

Resources