How to download Excel object in ASP.Net - c#

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

Related

An exception in reading data from excel using C# selenium web driver

I've a problem in reading data from Excel using selenium web driver. I've used "Microsoft.Office.Interop.Excel" and when running my code I found that exception
System.Runtime.InteropServices.Exception: Excel cannot access 'Downloads'. The document may be read only or encrypted.
enter image description here
This is the code I've used
public void sch_issue_1958M()
{
Application xlApp = new Application();
Workbook xlWorkBook = xlApp.Workbooks.Open(#"C:\Users\kkhatab\Desktop\3.0.0\Cube.Portal.Regression_for_issuesTests\bin\Downloads");
Worksheet xlWorkSheet = new Worksheet();
xlWorkSheet = xlWorkBook.Sheets[1];
Range xlRange = xlWorkSheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
//new line
if (j == 1)
Console.Write("\r\n");
//write the value to the console
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
}
Just for clarity for others:
Workbook xlWorkBook = xlApp.Workbooks.Open(#"C:\Users\kkhatab\Desktop\3.0.0\Cube.Portal.Regression_for_issuesTests\bin\Downloads");
You are trying to open a folder here rather than a document.

How to read an excel and do the mapping

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.

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;

Excel returns HRESULT: 0x800A03EC when the program is run by service (otherwise OK)

I have a Windows application that reads from a file and writes the contents into an Excel file. I have two modes of running this program. One is when the user is present and presses a button to generate the Excel file. And the program works fine in this mode. The other mode is when user schedules this job to be run by a Windows Service. And that is where I am getting the exception HRESULT: 0x800A03EC. Both these modes use the exact same code.
Please note that I do the exact procedure with .csv files and they work in both modes. .csv files do not use any COM components to be created and maybe that is why they can be done successfully.
This is the code for creating my Excel file.
Microsoft.Office.Interop.Excel.Application xlApp = null;
Workbook workbook = null;
Worksheet worksheet = null;
xlApp = new Microsoft.Office.Interop.Excel.Application();
workbook = xlApp.Workbooks.Add(1);
worksheet = (Worksheet)workbook.Sheets[1];
int columnCount = dt.Columns.Count;
int rowCount = dt.Rows.Count;
// Write header row
for (int i = 1; i <= columnCount; i++)
{
worksheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
// The rest
int lastIndex = 0;
for (int j = 1; j <= rowCount; j++)
{
for (int k = 1; k <= columnCount; k++)
worksheet.Cells[j + 1, k] = dt.Rows[j - 1][k - 1];
lastIndex = j + 1;
}
string path = string.Format("{0}\\{1}.xlsx", campaignOutputPath, campaignFileName);
if (File.Exists(path))
File.Delete(path);
xlApp.ActiveWorkbook.SaveAs(path, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlShared, false, false, Missing.Value, Missing.Value, Missing.Value);
workbook.Close();
xlApp.Quit();
Is it because creating a new Excel application cannot be done in the background? Because after a while of running this function in the background by the service, Windows shows me the following error:

Categories