I am trying to write this a set of data into a single column in excel with using a loop. I cant figure out why it currently does not write to different cells.
I have tried running this code and it shows up with just one of the values in the first cell that it should write in
foreach (Element e in wirelist)
{
Excel.Worksheet sheet =
(Excel.Worksheet)workbook.Worksheets.get_Item("Wires (Exported)");
int i = 3;
int j = 1;
((Excel.Range)sheet.Cells[i, j]).Value = e.Id;
i = i + 1;
}
It should print out a list of ID numbers in separate cells in the column.
Questions let me know!!
I think your issue is that you keep getting the Excel sheet and resetting i and j within the loop. Try this:
Excel.Worksheet sheet = (Excel.Worksheet)workbook.Worksheets.get_Item("Wires (Exported)");
int i = 3;
int j = 1;
foreach (Element e in wirelist)
{
((Excel.Range)sheet.Cells[i, j]).Value = e.Id;
i = i + 1;
}
Related
Basically what I need to do is, I have a lot of data that takes up 1 cell per row loaded into a datagridview, and I want to pivot it, and export it to an excel file. So what I have is a vertical list, and I would like to make it horizontal, but I only need the cells to be filled until getting to column 'L', and when the data gets to it, then it starts again at the next row, and repeating this until dgv has no more data to fill in to the excel.
So far what I have is:
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Worksheet xlsht = new Excel.Worksheet();
Microsoft.Office.Interop.Excel.Workbook xlwb;
xlApp.Visible = true;
string path = #"myfilepath";
xlwb = xlApp.Workbooks.Open(path);
xlsht = xlwb.Worksheets["Tabelle1"];
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 1; j < 12; j++)
{
xlsht.Cells[i + 1, j] = dataGridView1.Rows[i].Cells[0].Value.ToString();
}
}
The problem with this is the following: it fills the cells with the same value, until getting to the column 'L' (11th column, that's why I have 12 in the nested for loop), and then it starts again in the next row, but again, repeating the next value(to clarify, the value in the first row is 1, so it repeats 1 until getting to the 11th column.Then it starts again with the next value, for example 2, and does the same thing).
How could I fix this?
Thanks in advance!
You need to separate the Excel row and column indexes from the loop through the grids rows. All you need is one loop though all the rows to add the first column of that row to the worksheet. To keep it simple, pull the Excel indexs and manually update them.
In the loop through the rows, increment the worksheets column index by 1 until it reaches 12, Then increment the excel row index by 1 and reset the excel column back to 1.
Something likeā¦.
int xlRow = 1;
int xlCol = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
if (!dataGridView1.Rows[i].IsNewRow) {
xlsht.Cells[xlRow, xlCol] = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (xlCol == 12) {
xlRow++;
xlCol = 1;
}
else {
xlCol++;
}
}
}
I have a table in Word document. I want to able to select a row or column or only a cell or whole table to modify.
now I can select the complete table and modify all cells, but I can not select a single row or column or cell.
I can not create a range for this purpose.
below my code for select whole of table:
if (WordAddIn.Config.ApplicationConfig.TemplateLanguage.ValueToShare == true)
{
for (int i = 1; i <= WordManager.Selection.Tables[1].Rows.Count; i++)
{
for (int j = 1; j <= WordManager.Selection.Tables[1].Columns.Count; j++)
{
...
}
}
else
{ }
}
}
Thoughts?
Create a macro of what you need. Look at the VB calls of the macro and mimic/use those calls in your code.
You have to know the index of your table/row/column, but this is how you get the reference to each. From there, you can edit, delete, add, etc.
Word.Table myTable = Globals.ThisDocument.Tables[0];
//Get Row
Word.Row myRow = myTable.Rows[0];
//Get Column
Word.Column myCOl = myTable.Columns[0];
//Get Cell
int rowNum = 0;
int colNum = 0;
Word.Cell myCell = myTable.Cell(rowNum, colNum);
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'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.