Excel numberformatting - c#

I'm trying to create a excel from a datagrid with wpf, however when I format a column to just text it still converts some columns to what I presume to be a date conversion.
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
This is how the conversion of the column is set, but this results in Excel still formatting some fields to a date-ish value... If you look at the column foutcode you'll see what I mean.
results in:
I think what happens is that it automatically recognizes the value and sees if it fits a date format while I'm telling it to handle as just regular text! So does anyone have any idea on how to get rid of that? because the data is unusable because of this small error. Maybe use a more specific format than just text? however I can't seem to figure out how.
Also Convert a lot of rows into excel takes some quite a bit of time (4-5s for 1000 rows). Is there a way to make it go faster? All help is really appreciated.
public void ExportToExcel(List<Fouten> data)
{
try
{
if (data.Count > 0)
{
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = "Data rapport";
// If the User Clicks the Save Button then the Module gets executed otherwise it skips the scope
if ((bool)saveFileDialog1.ShowDialog())
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rowCount = 1;
xlWorkSheet.Cells[rowCount, 1] = "Datum";
xlWorkSheet.Cells[rowCount, 2] = "Tijd";
xlWorkSheet.Cells[rowCount, 3] = "Foutcode";
xlWorkSheet.Cells[rowCount, 4] = "Omschrijving";
xlWorkSheet.Cells[rowCount, 5] = "Module";
xlWorkSheet.Cells[rowCount, 6] = "TreinId";
rowCount++;
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 2];
rg.EntireColumn.NumberFormat = "hh:mm:ss.000";
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
foreach (Fouten item in data)
{
string[] moduleNaam = item.Module.Split('_');
xlWorkSheet.Cells[rowCount, 1] = item.Datum;
xlWorkSheet.Cells[rowCount, 2] = item.Time.ToString();
xlWorkSheet.Cells[rowCount, 3] = item.FoutCode;
xlWorkSheet.Cells[rowCount, 4] = item.Omschrijving;
xlWorkSheet.Cells[rowCount, 5] = moduleNaam[0].ToUpper();
xlWorkSheet.Cells[rowCount, 6] = item.TreinId;
rowCount++;
}
xlWorkSheet.Columns.AutoFit();
// If the file name is not an empty string open it for saving.
if (!String.IsNullOrEmpty(saveFileDialog1.FileName.ToString()) && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName.ToString()))
{
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel File Exported Successfully", "Export Engine");
}
}
}
}
else
{
MessageBox.Show("Nothing to Export", "Export Engine");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

The Range.NumberFormat property for Text is an 'at' symbol (e.g. capital 2 or #), not the word Text.
rg1.EntireColumn.NumberFormat = "#";
More at Number Format Codes.

Related

C# saving excel file not getting saved

I am using this code to create an excel instance which is used for making a report
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;
worKbooK = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worKsheeT = worKbooK.Worksheets[1]; ;
worKsheeT.Name = "Report";
iCountW = 2;
worKsheeT.Cells[1, 1] = "S.No";
worKsheeT.Cells[1, 2] = "Weld Stud/Nut Name";
worKsheeT.Cells[1, 3] = "Weld Spot Clearance Status";
worKsheeT.Cells[1, 4] = "Weld Spot Name";
worKsheeT.Cells[1, 5] = "Coord-X";
worKsheeT.Cells[1, 6] = "Coord-Y";
worKsheeT.Cells[1, 7] = "Coord-Z";
// Some Code
// Some more code
// No more code
After updating the data rows of this report I am using the below code for saving the excel workbook which is not letting me save the workbook.
string filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\" + "Trial_StudNut.xlsx";
if (!System.IO.File.Exists(filename))
{
worKbooK.SaveAs(filename, Excel.XlSaveAsAccessMode.xlNoChange);
}
Can someone help me with what am I missing to avoid exceptions while saving the workbook?
Edit: I am getting the following
(HRESULT: 0x800A03EC Error while saving Excel file)
The code is getting inside the condition and then falling into the exception.

interop error HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH) on server

I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.

Exporting SQL table to Excel in C# is randomly picking cells formats for dates

I am trying to export an SQL Dataset to an excel document.
At certain points when outputting the date fields the excel cells are being formatted at certain points as date cells and some as general.
This is causing the dates to display sometime in the format that I want, UK style day/month/year, in the American style month/day/year.
If it was just one way that would be fine because the report would be at least consistent. However the fact that the code will sometime output the correct format and sometimes won't is very annoying
My code so far:
private void doReport(DataSet myDS)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
int i;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Report produced on the " + System.DateTime.Now.ToString("dd/MM/yyyy");
xlWorkSheet.Cells[3, 1] = "Project Type";
xlWorkSheet.Cells[3, 2] = "Client";
xlWorkSheet.Cells[3, 3] = "Date Started";
xlWorkSheet.Cells[3, 4] = "Target Date";
xlWorkSheet.Cells[3, 5] = "Date Completed";
xlWorkSheet.Cells[3, 6] = "Stage Target";
xlWorkSheet.Cells[3, 7] = "Stage";
xlWorkSheet.Cells[3, 8] = "Assigned To";
xlWorkSheet.Cells[3, 9] = "Notes";
i = 4;
foreach (DataRow row in myDS.Tables[0].Rows)
{
xlWorkSheet.Cells[i, 1] = row["strProjectDescription"];
xlWorkSheet.Cells[i, 2] = row["strClient"];
DateTime dteProjStart = (DateTime)row["dteProjectStart"];
xlWorkSheet.Cells[i, 3] = dteProjStart.ToString("dd/MM/yyyy");
DateTime dteProjTarget = (DateTime)row["dteProjectTarget"];
xlWorkSheet.Cells[i, 4] = dteProjTarget.ToString("dd/MM/yyyy");
if (rbViewProjectsCompletedVal.Checked)
{
DateTime dteProjFin = (DateTime)row["dteProjectFinished"];
xlWorkSheet.Cells[i, 5] = dteProjFin.ToString("dd/MM/yyyy");
}
if (row.IsNull("dteProjectStageTarget") == false)
{
DateTime dteProjStageTar = (DateTime)row["dteProjectStageTarget"];
xlWorkSheet.Cells[i, 6] = dteProjStageTar.ToString("dd/MM/yyyy");
}
xlWorkSheet.Cells[i, 7] = row["strProjectStageDescription"];
xlWorkSheet.Cells[i, 8] = row["initials"];
xlWorkSheet.Cells[i, 9] = csSQL.runSQL("select strProjectNotes from tbl_AdminSupport_Projects where intASProjectID = " + row["intASProjectID"], "Management").Tables[0].Rows[0]["strProjectNotes"];
i++;
}
xlWorkSheet.Columns.AutoFit();
xlWorkSheet.Rows.AutoFit();
xlApp.Visible = true;
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Dataset structure:
Any item prefixed with str is a nvarchar(max), dte is a date

Create excel file and download it without saving it into the server, is it possible?

i have managed to create an excel file with interop, and now i want that excel file to be downloaded
in web browser instead of saving in in drive.
var xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
Excel.Range chartRange;
var attendance_list = CTX.schedules.Where(s => s.event_id == Convert.ToInt32(param));
if (attendance_list.Count() > 0)
{
xlWorkSheet.Cells[1, 1] = "PIC : ";
xlWorkSheet.Cells[2, 1] = "Tempat : ";
xlWorkSheet.Cells[1, 2] = attendance_list.FirstOrDefault().calendar_event.PIC;
xlWorkSheet.Cells[2, 2] = attendance_list.FirstOrDefault().calendar_event.sched_loc;
xlWorkSheet.Shapes.AddPicture(#Server.MapPath("~/Images/" + "oto_group2.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 100, 45);
xlWorkSheet.Shapes.AddPicture(#Server.MapPath("~/Images/" + "oto_group3.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 280, 50, 100, 45);
int row = 10;
int idx = 0;
xlWorkSheet.Cells[9, 1] = "No";
xlWorkSheet.Cells[9, 2] = "Name";
xlWorkSheet.Cells[9, 3] = "Phone";
xlWorkSheet.Cells[9, 4] = "Time";
xlWorkSheet.Cells[9, 5] = "Branch";
xlWorkSheet.Cells[9, 6] = "Sign";
xlWorkSheet.Cells[9, 7] = "Note";
chartRange = (xlWorkSheet.get_Range("b9"));
chartRange.ColumnWidth = 40;
chartRange = (xlWorkSheet.get_Range("c9"));
chartRange.ColumnWidth = 20;
chartRange = (xlWorkSheet.get_Range("g9"));
chartRange.ColumnWidth = 20;
var key = CTX.translate_value_ms.Where(t => t.PSF_type == "HRS_PHONE_TYPE"
&& t.value == "CELL").FirstOrDefault().translate_value_id;
foreach (var item in attendance_list)
{
idx++;
var hp = item.user_list.user_phones.Where(p => p.phone_type_id == key).FirstOrDefault();
xlWorkSheet.Cells[row, 1] = idx;
xlWorkSheet.Cells[row, 2] = displayFullName(item.user_list.fname, item.user_list.mname, item.user_list.lname);
xlWorkSheet.Cells[row, 3] = hp.phone_number;
xlWorkSheet.Cells[row, 4] = item.calendar_event.time_range;
xlWorkSheet.Cells[row, 5] = item.calendar_event.branch;
xlWorkSheet.Cells[row, 6] = "";
xlWorkSheet.Cells[row, 7] = "";
row++;
}
chartRange = xlWorkSheet.get_Range("a9", "g9");
chartRange.Font.Bold = true;
chartRange.Interior.Color = System.Drawing.Color.Gray;
chartRange = xlWorkSheet.get_Range("a9", "g" + (row - 1));
chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
this is what i have tried so far to create excel file. need some englightment. "this code save excel file to drive, which is not the result that i want to achieve."
this is my generated excel :
You will need to save the file on the server temporarily in order to serve it to the client.
You can save it in a temp path using utilities in System.IO.Path like GetTempPath() to put the file in a place the OS will clean the file up automatically when it's not needed.
I don't know what web server you're using but if you're using MVC you'd do something like this to serve the file in your controller
var filePath = System.IO.Path.GetTempFileName();
//then save the file to the filePath
return File(filePath);
I used https://npoi.codeplex.com/ to create excel and returned a FileStereamResult on my controller action.
I think you cannot do that with the Excel library you are using
How to write an Excel workbook to a MemoryStream in .NET?
But check out npoi is really simple and they even have an example on what you are looking, which was something like this
public FileStreamResult MyAction(parameters)
{
var workBook = CreateWorkbook(parameters);
var stream = new MemoryStream();
workBook.Write(stream);
stream.Position = 0;
return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
}
Like this you dont save anything to the file system.
Using a mix of your work and the example I made using NPOI you can do something like this
public FileStreamResult MyAction(parameters)
{
//Here you create a workBook with your actual code
var workBook = CreateWorkbook(parameters);
var fileName = "routeToFileWhereYourAppCanWrite.xls"
//Here you save the file to the file system
workbook.SaveToFile(fileName);
using (MemoryStream ms = new MemoryStream())
{
using (FileStream fileStream = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(ms);
}
//Here you delete the saved file
File.Delete(fileName);
ms.Position = 0;
return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
}
}
In summary, create the file as you do now, save it, load it into memory, delete it and return the stream
Paste this snippet code own project under Marshal.ReleaseComObject(xlApp); this line.
After that set path where your file save in system.
I hope this code will work.
string fileName = "";
Response.ContentType = "application/vnd.ms-excel";
fileName = Server.MapPath("~/WriteReadData/Excelfiles/Excelfile.xls");
//Give path name\file name.
Response.AppendHeader("Content-Disposition", "attachment; filename="Excelfile.xls");
//Specify the file name which needs to be displayed while prompting
Response.TransmitFile(fileName);
Response.End();

How can I dispose my Excel Application

My code is as follows
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file);
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange;
These are the only variables used in my function
foreach (Excel.Worksheet XLws in xlWorkbook.Worksheets)
{
// do some stuff
xlApp.UserControl = false;
if (xlRange != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlRange);
if (xlSheet != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlSheet);
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlRange = null;
xlSheet = null;
xlWorkbook = null;
xlApp.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
}
But still I get EXCEL.EXE in Task Manager
Please help?
Kill the excel process which has empty value for MainWindowTitle. Below is an example source code.
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
//Start Excel and get Application object.
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//Add table headers going cell by cell.
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.Cells[1, 4] = "Salary";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oSheet.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRng = oSheet.get_Range("D2", "D6");
oRng.Formula = "=RAND()*100000";
oRng.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRng = oSheet.get_Range("A1", "D1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
oWB.SaveAs("c:\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
oWB.Close(null, null, null);
oXL.Quit(); //MainWindowTitle will become empty afer being close
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWB);
Process[] excelProcesses = Process.GetProcessesByName("excel");
foreach (Process p in excelProcesses)
{
if (string.IsNullOrEmpty(p.MainWindowTitle)) // use MainWindowTitle to distinguish this excel process with other excel processes
{
p.Kill();
}
}
}
catch (Exception ex2)
{
}
You've got an implicit object left open. Try this
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks xlWorkbooks = xlApp.Workbooks;
Excel.Workbook xlWorkbook = xlWorkbooks.Open(file);
....
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlApp);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbooks);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
....
OK... I hope this helps... it took me forever to tweak this to get it to work just so...
Here is my entire function (VB -- but the C# code for the tricky stuff is in there (thanks to too many other stackoverflow giants who helped me get this far!)
Private Function ImportWorksFile() As Integer
Dim EndofSheet As Boolean
Dim BlankRowCounter As Integer
Dim rr As RowResult
Dim SecCount As Integer = 0
Dim SecRow As SecurityRow
Dim uf As New UtilFunctions
'If this has already been run, the instance of the excel object would have been 'killed' and needs to be reinstantiated
If blnExcelProcessKilled Then 'Global boolean var
xlApp = New Excel.Application()
blnExcelProcessKilled = False
End If
Dim excelProcess(0) As Process
excelProcess = Process.GetProcessesByName("excel")
Dim tmp As Excel.Workbooks
Try
tmp = xlApp.Workbooks
xlWorkBook = tmp.Open(WorkingFileName)
Catch ex As Exception
MessageBox.Show("There was a problem opening the workbook - please try again", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
End Try
Using dc As New AFLData(CurAFLApp, True)
Dim cmd As SqlCommand = DefineCommand()
cmd.CommandType = CommandType.StoredProcedure
For Each ws As Excel.Worksheet In xlWorkBook.Worksheets
Dim row As Integer = 1
EndofSheet = False
BlankRowCounter = 0
If ImpCols.ContainsKey(ws.Name) Then
SecRow = New SecurityRow(ImpCols(ws.Name))
Do Until EndofSheet
Try
SecRow.NewRow(ws.Rows(row))
rr = SecRow.IsValidRow
If rr = RowResult.Valid Then
' read this row and process
With cmd
.Parameters("#AcctDate").Value = FileDate
.Parameters("#NewSub").Value = SecRow.GetStrCell("newsub")
RunProcedure(cmd)
End With
SecCount += 1
BlankRowCounter = 0
Else
BlankRowCounter += rr
End If
Catch ex As Exception
MessageBox.Show("There was a problem with row: " & row & " in workbook " & ws.Name)
End Try
' if we've counted 50 blank A column values in a row, we're done.
If BlankRowCounter <= -50 Then
EndofSheet = True
End If
row += 1
Loop
End If
Next
End Using
Try
xlWorkBook.Close(SaveChanges:=False)
xlApp.Workbooks.Close()
xlApp.Quit()
'// And now kill the process. C# Version (for reference)
'if (processID != 0)
'{
' Process process = Process.GetProcessById(processID);
' process.Kill();
'}
' Reversed the order of release per http://stackoverflow.com/questions/12916137/best-way-to-release-excel-interop-com-object
Catch ex As Exception
MessageBox.Show("There was a problem CLOSING the workbook - Please double check that the data was imported correctly. ", CurAFLApp.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Return 0
Finally
releaseObject(tmp)
releaseObject(xlWorkBook)
releaseObject(xlApp)
If Not excelProcess(0).CloseMainWindow() Then
excelProcess(0).Kill()
blnExcelProcessKilled = True
End If
End Try
Return SecCount
End Function
Public Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
'Not sure if the following line helps or hinders -- seems to lock things up once in a while
'GC.WaitForPendingFinalizers()
End Try
End Sub
Try :
xlWorkbook.Close(false); // if you Workbook should not be saved
instead of :
if (xlWorkbook != null)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkbook);
xlWorkbook = null;

Categories