Application stop when exporting data to excel - c#

I have a code that displays a table from an Access database, on my WinForm I have an option to export the table to excel, once the user click on it takes some time to copy all rows to excel, if the user try to close the excel before all cells get transfer to the sheet the application will stop and throw the error System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x800AC472'
Here is the code for the "Export to Excel" button I have in my windows form
private void Export_btn_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
for (int i = 1; i < fviAoi_tbl.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = fviAoi_tbl.Columns[i - 1].HeaderText;
}
for (int i = 0; i < fviAoi_tbl.Rows.Count - 1; i++)
{
for (int j = 0; j < fviAoi_tbl.Columns.Count; j++)
{
if (fviAoi_tbl.Rows[i].Cells[j].Value != null)
{
worksheet.Cells[i + 2, j + 1] = fviAoi_tbl.Rows[i].Cells[j].Value.ToString();
}
else
{
worksheet.Cells[i + 2, j + 1] = "";
}
}
}
}
Any ideas why this is happening or how can I make my application to ignore that error and continue running.

Surround the code line that emit the exception with a try... catch...
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/

In general, Null is probably not what you think it is.
Null is not 0 nor empty string. Null is lack of data. What is the difference between ("") and (null)
Thus, C# and .NET probably throws an error here:
if (fviAoi_tbl.Rows[i].Cells[j].Value != null) because, it does not understand how can you compare some Excel cell with Null and what should it answer. Change the code to:
if (fviAoi_tbl.Rows[i].Cells[j].Value != "" or something similar.

Related

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.

Export to DataGrid To Excel in WPf

I want export to datagrid to wpf but when export an error is generated
An unhandled exception of type 'System.NullReferenceException' occurred in solutions.exe
my code...
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Worksheet sheet1 = (Worksheet)workbook.Sheets[1];
Range range;
Range myRange;
for (int i = 1; i < dgDatos.Columns.Count; i++)
{
range = (Range)sheet1.Cells[1, i + 1];
sheet1.Cells[1, i + 1].Font.Bold = true;
range.Value = dgDatos.Columns[i].Header;
for (int j = 0; j < dgDatos.Items.Count; j++)
{
TextBlock b = dgDatos.Columns[i].GetCellContent(dgDatos.Items[j]) as TextBlock;
myRange = sheet1.Cells[j + 2, i + 1];
myRange.Value = b.Text;
}
}
}
Without giving any indication of where the null value is, my bet would be on
myRange.Value = b.Text;
When you do this:
TextBlock b = dgDatos.Columns[i].GetCellContent(dgDatos.Items[j]) as TextBlock;
... b will be null if the object assigned to that cell is not a TextBlock.
For that matter, why have a TextBlock in the DataGrid? Check out DataTable.

How to hide Excel Columns and Rows using Interop C#

I have made a simple inventory interface that will take data from access and show in datagrid view on my interface and then send the information to Excel via button click. This part works as needed but I would like to remove the unused columns and rows after the information is sent. I am currently using VS 2015. I cant figure out what to add to accomplish this.
//send to excel
private void btnExport_Click(object sender, EventArgs e)
{
ActiveControl = txtSerial;
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Inventory Search";
// storing header part in Excel
for (int i = 1; i < dataGridFB.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridFB.Columns[i - 1].HeaderText;
worksheet.Cells[1, i].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
worksheet.Cells[1, i].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
worksheet.Cells[1, i].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[1, i].Font.Size = 14;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < dataGridFB.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridFB.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridFB.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, j + 1].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Cells[i + 2, j + 1].Font.Size = 12;
worksheet.Columns["A:G"].AutoFit();
}
}
}
Your question is a bit too broad, thus the answer is generic: in order to delete entire Worksheet Column you may use VBA statement like: Columns("C").Delete, or Columns(3).EntireColumn.Delete, or Columns("F:K").Delete. Similar syntax may apply to: Rows(3).Delete.
In order to just hide Rows/Columns use the VBA statement like shown below:
Rows("3:10").EntireRow.Hidden = True
Columns("C").Hidden = True
Hope this may help.

Reading an dynamic Excel File with C# error

I am trying to read an excel file with C# and display every cell in the sheet inside a messagebox using the messagebox.Show() method. Problem is that my excel file has 5 rows and 3 columns. here is my excel sheet: http://postimg.org/image/xts9n1kif.
It displays everything until "roof" and after that stops leaving behind "light" and "iron", but if i fill the stuff3 column it reads everything perfectly fine. As is my case, the file may change. It may have more columns or rows in it, and some of them may be empty.
Any idea why it is not working?
Here is my code:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ReadFromExcell
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new System.EventHandler(this.Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("C:\\Users\\User1\\Desktop\\ItemDB.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.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++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}
//Close the excel file after reading it.
xlWorkbook.Close();
}
}
}
Most likely what happens in your code is that when the loop hits cell C4 (which is empty) xlRange.Cells[i, j].Value2 becomes null.
Trying to invoke the ToString() method (or any other method, for that matter) on a null reference will cause a NullReferenceException.
Change your code inside your loop from...
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
...to something like that:
MessageBox.Show( (xlRange.Cells[i, j].Value2 ?? "<no value>").ToString() );
The ?? operator is handy in this situation. If the expression on the left side of ?? (that is xlRange.Cells[i, j].Value2) results in a null value, the ?? operator returns the value on the right-hand side of ?? instead.
(The cell C4 could contain a number of white-space characters, in which case the cell's value would not be null. But a cell with just a number of white-space characters is a rather unusual and rare occurrence.)
Now Try this..
for (int i = 0; i <= rowCount-1; i++)
{
for (int j = 0; j <= xlRange.Rows[0].Columns.Count-1; j++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}

C# COM Interop: Writing to a Cell in an Excel Sheet

I am using Microsoft.Office.Interop.Excel in a winform where I am reading one excel file, processing the data, and outputting a new excel file. However I am having trouble writing to the cells -- specifically to add column headings. Here's the code:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];
for (int i = 0; i < dt.Columns.Count; i++)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
ws.Cells[j + 1, i] = dt.Rows[j][i].ToString();
}
}
ws.Cells[0, 0] = "Ticket Number";
ws.Cells[0, 1] = "Transit";
ws.Cells[0, 2] = "Outage Start Date";
ws.Cells[0, 3] = "Outage End Date";
ws.Cells[0, 4] = "Business Impact";
wb.Worksheets.Add(ws);
where "dt" is my DataTable. The nested for-loop doesn't throw a runtime error but the code following it does. The error just says: COM Exception was unhandled, Exception from HRESULT: 0x800A03EC.
Any advice is appreciated.
Regards.
Cells[] is 1-based, not zero-based.

Categories