delete Style in Execl Using C# - c#

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.

Related

How to add xml schema/design file to Excel Interop?

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);

Copy from Excel using C#

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;

How to remove a column from excel sheet in epplus

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);
}
}

GemBox - For loop for rows and cols?

I have a question. Is there a way that I could go through all the cols/rows in a spreadsheet using a for loop?? Right now I am using foreach loops like this in my code: (You can just ignore what's going on inside).
foreach (ExcelRow row in w1.Rows)
{
foreach (ExcelCell cell in row.AllocatedCells)
{
Console.Write("row: {0}", globalVar.iRowActual);
if (globalVar.iRowActual > 1)
{
cellValue = SafeCellValue(cell);
Console.WriteLine("value is: {0}", cellValue);
}
}
globalVar.iRowActual++;
}
The problem is that I would like to assign the value of each cell to a new variable and pass it to another method. I would like to use for loops for this and I know I can use CalculateMaxUsedColumns as the limit for the cols but is there a property like that, that I could use for the rows?!
This is what I would like to do:
int columnCount = ws.CalculateMaxUsedColumns();
int rowCount = ws.CalculateMaxUsedRows(); ------> PART I NEED HELP WITH
for(int i=0; i <columnCount; i++){
for(int j = 0; j<rowCount; j++){
.....
}
}
Any kind of help would be greatly appreciated. Thanks!!!
Here is a way you can iterate in GemBox.Spreadsheet through all the columns / rows in a spreadsheet using a for loop.
Go through the CellRange which is returned by ExcelWorksheet.GetUsedCellRange method.
ExcelFile workbook = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets[0];
CellRange range = worksheet.GetUsedCellRange(true);
for (int r = range.FirstRowIndex; r <= range.LastRowIndex; r++)
{
for (int c = range.FirstColumnIndex; c <= range.LastColumnIndex; c++)
{
ExcelCell cell = range[r - range.FirstRowIndex, c - range.FirstColumnIndex];
string cellName = CellRange.RowColumnToPosition(r, c);
string cellRow = ExcelRowCollection.RowIndexToName(r);
string cellColumn = ExcelColumnCollection.ColumnIndexToName(c);
Console.WriteLine(string.Format("Cell name: {1}{0}Cell row: {2}{0}Cell column: {3}{0}Cell value: {4}{0}",
Environment.NewLine, cellName, cellRow, cellColumn, (cell.Value) ?? "Empty"));
}
}
EDIT
In newer versions there are some additional APIs which can simplify this. For instance, you can now use foreach and still retreive the row and column indexes with ExcelCell.Row.Index and ExcelCell.Column.Index and you can retreive the names without using those static methods (without RowColumnToPosition, RowIndexToName and ColumnIndexToName).
ExcelFile workbook = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets[0];
foreach (ExcelRow row in worksheet.Rows)
{
foreach (ExcelCell cell in row.AllocatedCells)
{
Console.WriteLine($"Cell value: {cell.Value ?? "Empty"}");
Console.WriteLine($"Cell name: {cell.Name}");
Console.WriteLine($"Row index: {cell.Row.Index}");
Console.WriteLine($"Row name: {cell.Row.Name}");
Console.WriteLine($"Column index: {cell.Column.Index}");
Console.WriteLine($"Column name: {cell.Column.Name}");
Console.WriteLine();
}
}
Also, here are two other ways how you can iterate through sheet cells in for loop.
1) Use ExcelWorksheets.Rows.Count and ExcelWorksheets.CalculateMaxUsedColumns() to get the last used row and column.
ExcelFile workbook = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets[0];
int rowCount = worksheet.Rows.Count;
int columnCount = worksheet.CalculateMaxUsedColumns();
for (int r = 0; r < rowCount; r++)
{
for (int c = 0; c < columnCount; c++)
{
ExcelCell cell = worksheet.Cells[r, c];
Console.WriteLine($"Cell value: {cell.Value ?? "Empty"}");
Console.WriteLine($"Cell name: {cell.Name}");
Console.WriteLine($"Row name: {cell.Row.Name}");
Console.WriteLine($"Column name: {cell.Column.Name}");
Console.WriteLine();
}
}
If you have a non-uniform spreadsheet in which rows have different column count (for instance, first row has 10 cells, second row has 100 cells, etc.), then you could use the following change in order to avoid iterating through non-allocated cells:
int rowCount = worksheet.Rows.Count;
for (int r = 0; r < rowCount; r++)
{
ExcelRow row = worksheet.Rows[r];
int columnCount = row.AllocatedCells.Count;
for (int c = 0; c < columnCount; c++)
{
ExcelCell cell = row.Cells[c];
// ...
}
}
2) Use CellRange.GetReadEnumerator method, it iterates through only already allocated cells in the range.
ExcelFile workbook = ExcelFile.Load("Sample.xlsx");
ExcelWorksheet worksheet = workbook.Worksheets[0];
CellRangeEnumerator enumerator = worksheet.Cells.GetReadEnumerator();
while (enumerator.MoveNext())
{
ExcelCell cell = enumerator.Current;
Console.WriteLine($"Cell value: {cell.Value ?? "Empty"}");
Console.WriteLine($"Cell name: {cell.Name}");
Console.WriteLine($"Row name: {cell.Row.Name}");
Console.WriteLine($"Column name: {cell.Column.Name}");
Console.WriteLine();
}

Convert a jagged array to a 2D array directly without iterating each item?

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);
}
}

Categories