Hi my dear friends i have question about excel stuff in C#. I have matrix table in below image.
I have to convert it to tabular table with C# console like in below image.
Can you help me about it?
What I believe you want is an "unpivot." Here is a very basic example, based on your sample data, of how you might unpivot this data using C# and Excel Interop:
Excel.Worksheet ws1 = excel.ActiveWorkbook.Sheets[1];
Excel.Worksheet ws2 = excel.ActiveWorkbook.Sheets[2];
int newRow = 5;
for (int col = 2; col <= 6; col++)
{
string kalipTipi = ws1.Cells[4, 1].Value.ToString();
string figur = ws1.Cells[5, col].Value.ToString();
for (int row = 6; row <= 13; row++)
{
string ebat = ws1.Cells[row, 1].Value.ToString();
Excel.Range r = ws2.Rows[string.Format("{0}:{0}", newRow++)];
r.Cells[1, 1].Value = kalipTipi;
r.Cells[1, 2].Value = figur;
r.Cells[1, 3].Value = ebat;
r.Cells[1, 4].Value = ws1.Cells[row, col].Value;
}
}
Short of knowing what the rest of your worksheet looks like, it's hard to say how scalable this is, but it's at least a template for what you're trying to accomplish.
Related
I need to read an excel file after reading it I need to do a mapping
to a DataGridView.
This is the code I've tried:
DataTable dt = new DataTable();
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\HP8200\Desktop\2003.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs = exlWb.Sheets["PARAC1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row - 1; j++)
{
for (int k = 1; k <= col - 1; k++)
{
cellValue[j, k] = exlWs.Cells[j, k + 1].ToString();
dt.Rows[j]["Customer No"] = cellValue[j, 1];
dt.Rows[j]["Card Prog"] = cellValue[j, 2];
dt.Rows[j]["LOS No"] = cellValue[j, 3];
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
dataGridView1.DataSource = dt;
there are some good answers here:
How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries
It is always a good idea to read an excel file without being required to have office installed and you will see there an answer related to this, there are libraries that can do that for you easily.
Next, try to apply a little SOC ( separation of concerns ) in your code. This means you build a layer responsible for reading your excel files and that one returns some data in a format you can use in the UI. That's the layer you call and then you apply the results of that call to your DataGrid or whatever other UI thing you want to display it in.
I have made a simple inventory interface that will take data from access and show in datagrid view on my interface and then send the information to Excel via button click. This part works as needed but I would like to remove the unused columns and rows after the information is sent. I am currently using VS 2015. I cant figure out what to add to accomplish this.
//send to excel
private void btnExport_Click(object sender, EventArgs e)
{
ActiveControl = txtSerial;
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Inventory Search";
// storing header part in Excel
for (int i = 1; i < dataGridFB.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridFB.Columns[i - 1].HeaderText;
worksheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
worksheet.Cells[1, i].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
worksheet.Cells[1, i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[1, i].Font.Size = 14;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridFB.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridFB.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridFB.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, j + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[i + 2, j + 1].Font.Size = 12;
worksheet.Columns["A:G"].AutoFit();
}
}
}
Your question is a bit too broad, thus the answer is generic: in order to delete entire Worksheet Column you may use VBA statement like: Columns("C").Delete, or Columns(3).EntireColumn.Delete, or Columns("F:K").Delete. Similar syntax may apply to: Rows(3).Delete.
In order to just hide Rows/Columns use the VBA statement like shown below:
Rows("3:10").EntireRow.Hidden = True
Columns("C").Hidden = True
Hope this may help.
I have an Excel file and I need to copy data from one column. But I don't know how many rows are there.
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook _workBook = xlApp.Workbooks;
Excel.Worksheet _workSheet = (Excel.Worksheet) _workBook.Worksheets[1];
How can I copy data?
Range range = _workSheet .UsedRange;
int rows = range.Rows.Count;
int cols = range.Columns.Count;
// nested loops to take values from used range of cell one by one
for(int r=1; r <= rows; r++)
for(int c=1; c <= cols; c++)
object cellValue = range.Cells[r,c].Value2;
// take values from one row
int row = 1;
for(int c=1; c <= cols; c++)
object cellValue = range.Cells[row,c].Value2;
since you didn't provide any information about the library you are using for working with excel, i will assume you are using Interop Services:
int columns = _workSheet.Columns.Count;
int rows = _workSheet.Rows.Count;
int cells = columns*rows
string cellValue = (string)((Excel.Range)_workSheet.Cells[1, 1]).Value;
A rather higeisch dataset with 16000 x 12 entries needs to be dumped into a worksheet.
I use the following function now:
for (int r = 0; r < dt.Rows.Count; ++r)
{
for (int c = 0; c < dt.Columns.Count; ++c)
{
worksheet.Cells[c + 1][r + 1] = dt.Rows[r][c].ToString();
}
}
I rediced the example to the center piece
Here is what i implemented after reading the suggestion from Dave Zych.
This works great.
private static void AppendWorkSheet(Excel.Workbook workbook, DataSet data, String tableName)
{
Excel.Worksheet worksheet;
if (UsedSheets == 0) worksheet = workbook.Worksheets[1];
else worksheet = workbook.Worksheets.Add();
UsedSheets++;
DataTable dt = data.Tables[0];
var valuesArray = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; ++r)
{
for (int c = 0; c < dt.Columns.Count; ++c)
{
valuesArray[r, c] = dt.Rows[r][c].ToString();
}
}
Excel.Range c1 = (Excel.Range)worksheet.Cells[1, 1];
Excel.Range c2 = (Excel.Range)worksheet.Cells[dt.Rows.Count, dt.Columns.Count];
Excel.Range range = worksheet.get_Range(c1, c2);
range.Cells.Value2 = valuesArray;
worksheet.Name = tableName;
}
Build a 2D array of your values from your DataSet, and then you can set a range of values in Excel to the values of the array.
object valuesArray = new object[dataTable.Rows.Count, dataTable.Columns.Count];
for(int i = 0; i < dt.Rows.Count; i++)
{
//If you know the number of columns you have, you can specify them this way
//Otherwise use an inner for loop on columns
valuesArray[i, 0] = dt.Rows[i]["ColumnName"].ToString();
valuesArray[i, 1] = dt.Rows[i]["ColumnName2"].ToString();
...
}
//Calculate the second column value by the number of columns in your dataset
//"O" is just an example in this case
//Also note: Excel is 1 based index
var sheetRange = worksheet.get_Range("A2:O2",
string.Format("A{0}:O{0}", dt.Rows.Count + 1));
sheetRange.Cells.Value2 = valuesArray;
This is much, much faster than looping and setting each cell individually. If you're setting each cell individually, you have to talk to Excel through COM (for lack of a better phrase) for each cell (which in your case is ~192,000 times), which is incredibly slow. Looping, building your array and only talking to Excel once removes much of that overhead.
I am trying to save a DataTable into an excel sheet.. my code is like this..
Excel.Range range = xlWorkSheet.get_Range("A2");
range = range.get_Resize(dtExcel.Rows.Count, dtExcel.Columns.Count);
object[,] rng1 = new object[dtExcel.Rows.Count, dtExcel.Columns.Count];
Excel range requires range value as array[,] but I have the DataTable as jagged array[][].
object[][] rng2 = dtExcel.AsEnumerable().Select(x => x.ItemArray).ToArray();
Is there any built-in function to directly convert the jagged array[][] to a 2D array[][] ?
Iterating through Excel, DataTable and assigning seems slower with bulk data..
Also I don't want to setup querying with DSN for excel.. I chose excel storage to avoid the configuring of any databases.. :P
I found a detailed explanation of ways of writing data to excel here..
http://support.microsoft.com/kb/306023
At last I used NPOI library for this. It is quite simple and free.
The code to convert DataTable to excel as follows.
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
foreach (DataTable dt in DataSource.Tables)
{
ISheet sheet1 = hssfworkbook.CreateSheet(dt.TableName);
//Set column titles
IRow headRow = sheet1.CreateRow(0);
for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
{
ICell cell = headRow.CreateCell(colNum);
cell.SetCellValue(dt.Columns[colNum].ColumnName);
}
//Set values in cells
for (int rowNum = 1; rowNum <= dt.Rows.Count; rowNum++)
{
IRow row = sheet1.CreateRow(rowNum);
for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
{
ICell cell = row.CreateCell(colNum);
cell.SetCellValue(dt.Rows[rowNum - 1][colNum].ToString());
}
}
// Resize column width to show all data
for (int colNum = 0; colNum < dt.Columns.Count; colNum++)
{
sheet1.AutoSizeColumn(colNum);
}
}