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.
Related
I am creating an excel file using a data table in excel interop
Price Profit/Loss%
250.8982989 0.04301071
I have a schema file which has details for design as
1) make all headers bold
2) column definition (weather,string,percentage)
I used this file in fast report export but as such i have to use interop for excel export is there a way i can add that schema file
Excel.Application excelApp = new Excel.Application();
//Create an Excel workbook instance and open it from the predefined location
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
//Add a new worksheet to workbook with the Datatable name
Excel.Worksheet excelWorkSheet = (Excel.Worksheet)excelWorkBook.Sheets.Add();
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
excelWorkBook.SaveAs(#"D:\sample excel.xls");
excelWorkBook.Close();
excelApp.Quit();
i want to show this value in bold and format as % 0.04301071
make this value Bold and round 250.8982989
This all information will be stored in a schema file i want to load that file
or else i want to load that cell as per the columns datatype in datatable
I have tried :-
clmnrange.NumberFormat = (Object)table.Columns[k - 1].DataType;
but it is raising an exception
Regards
EP
As mentioned in above comment:
The NumberFormat property takes a string that uses Excel's formatting
syntax. For example formatting as a percentage (up to) 8 decimal
places is "0.########%"
Here is an example that someone else provided showing how to implement the type of numberingFormat you are describing:
WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();
Create a stylesheet:
sp.Stylesheet = new Stylesheet();
Create a numberingFormat:
sp.Stylesheet.NumberingFormats = new NumberingFormats();
// #.##% is also Excel style index 1
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);
nf2decimal.FormatCode = StringValue.FromString("0.0%");
sp.Stylesheet.NumberingFormat.Append(nf2decimal);
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.
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'm using csharp to insert data into excel sheet into 7 columns. The interface of this program will allow users to select 7 checkboxes. If they select all 7, all the 7 columns in spreadhseet will have data, if they select one checkbox then only one column will have data. I have got a for loop which will check if data is there, if no data exists, I want to remove that column in epplus. Here's a previous discussion on this topic
How can I delete a Column of XLSX file with EPPlus in web app
It's quiet old so I just wanna check if there's a way to do this.
Or, is there a way to cast epplus excel sheet to microsoft interop excel sheet and perform some operations.
Currently, I've code like this:
for(int j=1; j <= 9; j++) //looping through columns
{
int flag = 0;
for(int i = 3; i <= 10; i++) // looping through rows
{
if(worksheet.cells[i, j].Text != "")
{
flag ++;
}
}
if (flag == 0)
{
worksheet.column[j].hidden = true; // hiding the columns- want to remove it
}
}
Can we do something like:
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp = worksheet; (where worksheet is epplus worksheet)
Are you using EPPlus 4? The ability to do column inserts and deletion was added with the new Cell store model they implemented. So you can now do something like this:
[TestMethod]
public void DeleteColumn_Test()
{
//http://stackoverflow.com/questions/28359165/how-to-remove-a-column-from-excel-sheet-in-epplus
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.Add(new DataColumn("Col1"));
datatable.Columns.Add(new DataColumn("Col2"));
datatable.Columns.Add(new DataColumn("Col3"));
for (var i = 0; i < 20; i++)
{
var row = datatable.NewRow();
row["Col1"] = "Col1 Row" + i;
row["Col2"] = "Col2 Row" + i;
row["Col3"] = "Col3 Row" + i;
datatable.Rows.Add(row);
}
using (var pack = new ExcelPackage(existingFile))
{
var ws = pack.Workbook.Worksheets.Add("Content");
ws.Cells.LoadFromDataTable(datatable, true);
ws.DeleteColumn(2);
pack.SaveAs(existingFile);
}
}
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.