Copy from Excel using C# - 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;

Related

delete Style in Execl Using 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.

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

How to download Excel object in ASP.Net

Please consider this code:
Microsoft.Office.Interop.Excel.Application objApp;
Microsoft.Office.Interop.Excel._Workbook objBook;
Microsoft.Office.Interop.Excel.Workbooks objBooks;
Microsoft.Office.Interop.Excel.Sheets objSheets;
Microsoft.Office.Interop.Excel._Worksheet objSheet;
Microsoft.Office.Interop.Excel.Range range;
int ColumnsCount = dt.Columns.Count;
int RowsCount = dt.Rows.Count;
objApp = new Microsoft.Office.Interop.Excel.Application();
objBooks = objApp.Workbooks;
objBook = objBooks.Add(System.Reflection.Missing.Value);
objSheets = objBook.Worksheets;
objSheet = (Microsoft.Office.Interop.Excel._Worksheet)objSheets.get_Item(1);
for (int i = 1; i < ColumnsCount + 1; i++)
{
objSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
range = objSheet.get_Range("A2", System.Reflection.Missing.Value);
range = range.get_Resize(RowsCount, ColumnsCount);
string[,] saRet = new string[RowsCount, ColumnsCount];
for (int iRow = 0; iRow < RowsCount; iRow++)
{
for (int iCol = 0; iCol < ColumnsCount; iCol++)
{
saRet[iRow, iCol] = dt.Rows[iRow][iCol].ToString();
}
}
//Set the range value to the array.
range.set_Value(Missing.Value, saRet);
I want to download Excel object that I created. The problem is Microsoft.Office.Interop.Excel._Workbook is not serializable and until I save it I can't access Excel file. How I can download Excel that created in memory?
thanks
This seems like one of the many problems related to Microsoft KB: Considerations for server-side Automation of Office. Using Excel Interop server-side isn't supported.
I'd recommend you export csv files or look into OpenXML or the easier version ClosedXML to generate xslx files on the server.
See the other methods in this MSDN guide: How To Asp.Net Export Excel
There should be a SaveAs method on your workbook that you can use to save as an xls file.
objBook.SaveAs("my-workbook.xls");

Fastest way to drop a DataSet into a worksheet

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.

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