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);
}
}
Related
trying to get a value from a data table, and output its contents to a textbox. seems im nearly there but for some reason studio doesnt like dt.rows[][];
ive seen multiple examples online in this format, but i get error CS002, cannot apply indexing with [] to an expression of type 'DataGridViewRow'.
im trying to locate the current row, and i can figure out the column either by putting an index number or by using the name of the column if that works better.
here is datatable_selectionChanged
private void dt_SelectionChanged(object sender, EventArgs e)
{
int row = dt.CurrentCell.RowIndex;
int col = dt.CurrentCell.ColumnIndex;
textBox1.Text = Convert.ToString(row);
textBox2.Text = Convert.ToString(col);
}
here is my mainform_load
private void mainForm_Load(object sender, EventArgs e)
{
string file = #"C:\Users\User\OneDrive - Motion Controls Robotics, Inc\Desktop\test inventory\TIS.xlsm"; //variable for the Excel File Location
DataTable dt = new DataTable(); //container for our excel data
DataRow row;
try
{
//Create Object for Microsoft.Office.Interop.Excel that will be use to read excel file
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(file);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = excelWorkbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count; //get row count of excel data
int colCount = excelRange.Columns.Count;//number of columns to display
//Get the first Column of excel file which is the Column Name
for (int i = 2; i <= rowCount;)
{
for (int j = 1; j <= colCount; j++)
{
dt.Columns.Add(excelRange.Cells[i, j].Value2.ToString());
}
break;
}
//Get Row Data of Excel
int rowCounter; //This variable is used for row index number
for (int i = 3; i <= rowCount; i++) //Loop for available row of excel data
{
row = dt.NewRow(); //assign new row to DataTable
rowCounter = 0;
for (int j = 1; j <= colCount; j++) //Loop for available column of excel data
{
//check if cell is empty
if (excelRange.Cells[i, j] != null && excelRange.Cells[i, j].Value2 != null)
{
row[rowCounter] = excelRange.Cells[i, j].Value2.ToString();
}
else
{
excelRange.Cells[i, j].value2 = "Empty";
//row[i] = "";
}
rowCounter++;
}
dt.Rows.Add(row); //add row to DataTable
}
this.dt.DataSource = dt; //assign DataTable as Datasource for DataGridview
//close and clean excel process
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(excelRange);
Marshal.ReleaseComObject(excelWorksheet);
//quit apps
excelWorkbook.Close();
Marshal.ReleaseComObject(excelWorkbook);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
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 created Excel file using this code:
Sheets worksheets = wb.Sheets;
Worksheet worksheet = (Worksheet)worksheets[4];
int rows = dt.Rows.Count;
int columns = dt.Columns.Count;
var data = new object[rows + 1, columns];
for (var column = 0; column < columns; column++)
{
data[0, column] = dt.Columns[column].ColumnName;
}
for (var row = 0; row < rows; row++)
{
for (var column = 0; column < columns; column++)
{
data[row + 1, column] = dt.Rows[row][column];
}
}
Range beginWrite = (Range)worksheet.Cells[1, 1];
Range endWrite = (Range)worksheet.Cells[rows + 1, columns];
Range sheetData = worksheet.Range[beginWrite, endWrite];
sheetData.Value2 = data;
worksheet.Select();
sheetData.Worksheet.ListObjects.Add(XlListObjectSourceType.xlSrcRange,
sheetData,
Type.Missing,
XlYesNoGuess.xlNo,
Type.Missing);
sheetData.Select();
Excel.ActiveWindow.DisplayGridlines = false;
Excel.Application.Range["2:2"].Select();
Excel.Application.Range["$A$3"].Select();
the problem here it set default format style to excel fileI don't know how to clear all format style in excel sheet
If all you are trying to do is delete all styles, this would work:
using Excelx = Microsoft.Office.Interop.Excel;
Excelx.Workbook wb = excel.ActiveWorkbook;
foreach (Excelx.Style st in wb.Styles)
st.Delete();
Then again, you may only want to clear out custom styles (not the ones that come standard), in which case a small modification would do it:
foreach (Excelx.Style st in wb.Styles)
{
if (!st.BuiltIn)
st.Delete();
}
Styles are stored at the workbook level, so at some point you need to declare your workbook. From there, the Styles collection of the Workbook object has everything you need.
I populate values from my gridview in my table using this Code:
Table table = new Table();
// get gridlines from gridview
table.GridLines = GridView1.GridLines;
if (GridView1.HeaderRow != null)
{
table.Rows.Add(GridView1.HeaderRow);
}
foreach (GridViewRow row in GridView1.Rows)
{
table.Rows.Add(row);
}
if (GridView1.FooterRow != null)
{
table.Rows.Add(GridView1.FooterRow);
}
What I need is to read every data from the table which contains the values of the gridview into an Excel worksheet cell.
How can I achieve this?
PS: This is my worksheet obj in code-behind in C#.
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Or Is there any other way to add the data from GridView to something else than, using table, which can be easily read?
public void ExportToExcel()
{
var Excel = new Microsoft.Office.Interop.Excel.Application();
XlReferenceStyle RefStyle = Excel.ReferenceStyle;
Excel.Visible = true;
Workbook wb = null;
string path = "yourpath";
try
{
wb = Excel.Workbooks.Add(path);
}
catch (System.Exception ex)
{
throw new Exception(ex.Message);
}
Worksheet ws = wb.Worksheets.get_Item(1) as Worksheet ;
for (int j = 0; j < GridView1.Columns.Count; ++j)
{
(ws.Cells[1, j + 1] as Range).Value2 = GridView1.Columns[j].HeaderText;
for (int i = 0; i < GridView1.Rows.Count; ++i)
{
object Val = GridView1.Rows[i].Cells[j].Value;
if (Val != null)
(ws.Cells[i + 2, j + 1] as Range).Value2 = Val.ToString();
}
}
Excel.ReferenceStyle = RefStyle;
Marshal.ReleaseComObject((object)Excel);
GC.GetTotalMemory(true);
}
Yes, there is a number of ways depending of what you gonna do. In your case the easiest one is CSV file (that would be work with Excel excellent). And there is no need to do somethins with DataGridView, if you have a DataSource
I am trying to import an excel file into a data table using GemBox and I keep getting this error:
Invalid data value when extracting to DataTable at SourceRowIndex: 1, and SourceColumnIndex: 1.
As far as I can tell my code is correct and my file is file fine. Does anyone have any ideas?
Thanks.
ExcelWorksheet Ew = ExFi.Worksheets[0];
for (int i = 0; i < Ew.Columns.Count; ++i)
{
if (Ew.Rows[0].Cells[0, i].Value != null)
dsTable.Columns.Add(Ew.Rows[0].Cells[0, i].Value.ToString(), typeof(string));
}
try
{
Ew.ExtractToDataTable(dsTable, Ew.Rows.Count, ExtractDataOptions.StopAtFirstEmptyRow, Ew.Rows[1], Ew.Columns[0]);
}
GemBox.Spreadsheet component doesn't automatically convert numbers to strings in ExtractToDataTable() method.
That's mainly because of the culture issues; someone would expect that number 12.4 is converted to "12.4" and someone else to "12,4".
So if your Excel file has cell with the value of type int, and corresponding column is of type string -> an exception would be thrown. To override that, you can use ExcelWorksheet.ExtractDataEvent.
Here's sample:
// Create new ExcelFile
ExcelFile ef = new ExcelFile();
// Add sheet
ExcelWorksheet ws = ef.Worksheets.Add("Sheet1");
// Fill sheet
for (int i = 0; i < 5; i++)
{
ws.Cells[i, 0].Value = i; // integer value
ws.Cells[i, 1].Value = "Row: " + i; // string value
}
// Initialize DataTable
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("text", typeof(string));
// Manage ExtractDataError.WrongType error
ws.ExtractDataEvent += (sender, e) =>
{
if (e.ErrorID == ExtractDataError.WrongType)
{
e.DataTableValue = e.ExcelValue == null ? null : e.ExcelValue.ToString();
e.Action = ExtractDataEventAction.Continue;
}
};
// Extract data to DataTable
ws.ExtractToDataTable(dt, 1000, ExtractDataOptions.StopAtFirstEmptyRow, ws.Rows[0], ws.Columns[0]);
I had the some issue, i overcame it by explicitly accessing worksheet cells
DataTable dtResult = new DataTable();
int nRows = ws.Rows.Count;
int nCols = 3; //change this according to number of columns in your sheet, for some reason ws.columns.count returns 0
for (int i = 0; i < nCols ; i++)
dtResult.Columns.Add();
for (int i = 0; i < nRows; i++)
{
if (ws.Cells[i, 0].Value != null)
dtResult.Rows.Add(ws.Cells[i, 0].Value.ToString(), ws.Cells[i, 1].Value.ToString(), ws.Cells[i, 2].Value.ToString());
}
return dtResult;
I had the same problem. I'd been using Typed DataSets so when I tried to populate one of my tables I had that error.
The problem here is the decimal numbers in the Excel file. Initialy I assigned the columns with decimal values to System.Decimal and that error was thrown.
The solution is to change the Type of the Column to System.Double. Why? I don't know, but it worked.