Exporting from WPF to Excel - c#

I created a WinForm that adds data from textboxs to a List and then when the form closes, exports that data to an excel spreadsheet. I'm in the process of trying to convert my WinForm to a WPF, and the code is no longer working. I'm not getting any errors, it just isn't creating the spreadsheet. Am I missing something here?
protected void OnFormClosing(object sender, EventArgs e)
{
if(signees.Count > 0)
{
initExcelSheet();
}
}
public void initExcelSheet()
{
EXL.Application oXL;
EXL._Workbook oWB;
EXL._Worksheet oWS;
EXL.Range oRng;
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oWS = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oWS.Cells[1, 1] = "First Name";
oWS.Cells[1, 2] = "Last Name";
oWS.Cells[1, 3] = "Email";
oWS.Cells[1, 4] = "Expected Graduation Date";
oWS.Cells[1, 5] = "School";
oWS.Cells[1, 6] = "Major";
oWS.Cells[1, 7] = "Favorite Languages";
oWS.get_Range("A1", "G1").Font.Bold = true;
oWS.get_Range("A1", "G1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
int count = 2;
foreach(Person x in signees)
{
oWS.Cells[count, 1] = x.firstName;
oWS.Cells[count, 2] = x.lastName;
oWS.Cells[count, 3] = x.email;
oWS.Cells[count, 4] = x.gradDate.ToString("yyyy-MM-dd");
oWS.Cells[count, 5] = x.schoolName;
oWS.Cells[count, 6] = x.fos;
oWS.Cells[count, 7] = x.fcl;
count += 1;
}
oRng = oWS.get_Range("A1", "G1");
oRng.EntireColumn.AutoFit();
try
{
oWB.SaveAs(fileName(school, DateTime.Now));
}
catch(Exception e)
{
Console.Write(e.ToString());
}
oWB.Close();

Related

Missing value when export listview to xls file in c#

The problem is i can export listview to excel file successfully, but when i try to open it. They said it can read only. And some value in file is change to '0'
Example:
10379743021704072015 -> 10379743021704000000
10379743021704072015 -> 1.0379743021704E+019
Note: I use Microsoft excel 2016 to open it.
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel
Workbook|*.xlsx", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Workbook wb =
app.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)app.ActiveSheet;
app.Visible = false;
ws.Cells[1, 1] = "date";
ws.Cells[1, 2] = "time";
ws.Cells[1, 3] = "harness";
ws.Cells[1, 4] = "ModuleHtr";
ws.Cells[1, 5] = "MainIp";
ws.Cells[1, 6] = "Antenna";
ws.Cells[1, 7] = "AirBag";
ws.Cells[1, 8] = "Screw Torque 1";
ws.Cells[1, 9] = "Screw Torque 2";
ws.Cells[1, 10] = "Screw Torque 3";
ws.Cells[1, 11] = "Scan Switch";
ws.Cells[1, 12] = "Cluster";
ws.Cells[1, 13] = "E-Test AirBag";
ws.Cells[1, 14] = "E-Test Cluster";
ws.Cells[1, 15] = "E-Test Column";
ws.Cells[1, 16] = "E-Test Sensor";
ws.Cells[1, 17] = "E-Test Result";
ws.Cells[1, 18] = "QC (Ok or Nok)";
ws.Cells[1, 19] = "Serial Number";
int i = 2;
foreach (ListViewItem item in listView1.Items)
{
ws.Cells[i, 1] = item.SubItems[0].Text;
ws.Cells[i, 2] = item.SubItems[1].Text;
ws.Cells[i, 3] = item.SubItems[2].Text;
ws.Cells[i, 4] = item.SubItems[3].Text;
ws.Cells[i, 5] = item.SubItems[4].Text;
ws.Cells[i, 6] = item.SubItems[5].Text;
ws.Cells[i, 7] = item.SubItems[6].Text;
ws.Cells[i, 8] = item.SubItems[7].Text;
ws.Cells[i, 9] = item.SubItems[8].Text;
ws.Cells[i, 10] = item.SubItems[9].Text;
ws.Cells[i, 11] = item.SubItems[10].Text;
ws.Cells[i, 12] = item.SubItems[11].Text;
ws.Cells[i, 13] = item.SubItems[12].Text;
ws.Cells[i, 14] = item.SubItems[13].Text;
ws.Cells[i, 15] = item.SubItems[14].Text;
ws.Cells[i, 16] = item.SubItems[15].Text;
ws.Cells[i, 17] = item.SubItems[16].Text;
ws.Cells[i, 18] = item.SubItems[17].Text;
ws.Cells[i, 19] = item.SubItems[18].Text;
i++;
}
wb.SaveAs(sfd.FileName, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, true, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
MessageBox.Show("Exported");
}
}
Each time you run the Save option, you are creating a workbook, but not closing it, so it is read only. Even when you stop debugging or close your program, it will still be read only.
You need to close the workbook each time you run your save command. So you need to add the workbook close statement to the end of your code like this:
MessageBox.Show("Exported")
wb.Close();

C# Excel Write to multiple cells

Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.

Load excel sheet with c#

First i apologize for the mistakes in my text, english is not my native language and i do my best.
I'm a very beginner in coding and i have a little question about loading an excel sheet.
I'm trying to do a project with vb in c# and i have to load an excel sheet which already exist and write in it. I found some explanations who help me to create a New sheet and write in it :
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
oXL = new Excel.Application("Exemple.xlsx");
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
oSheet.get_Range("A2", "B6").Value2 = saNames;
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
The things i write don't really matter but i can't load my own sheet. I tought by replacing
oXL = new Excel.Application();
by
oXL = new Excel.Application("Exemple.xlsx");
I could load my sheet ( call Exemple.xlsx)
Unfortunately it don't work, could you tell me what's wrong?
Thanks!
Once you have your reference to Excel, you must call the Workbooks.Open method to open an existing file:
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Open("Example.xlsx"));

Issue regarding Excel Line chart generation from c# code

I am trying to generate line chart from datatable but output is not coming fine. i guess there is axis related problem is there. so it will be great help if some one rectify my code.
private void button1_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = GetGraphData();
Excel.Application xla = new Excel.Application();
xla.Visible = true;
Excel.Workbook wb = xla.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = chartObjs.Add(250, 60, 300, 300);
Excel.Chart xlChart = chartObj.Chart;
int nRows = 2;
int nColumns = dt.Rows.Count;
string upperLeftCell = "B2";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1))
+ nRows - 1;
char endColumnLetter = System.Convert.ToChar(
Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}",
endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}",
endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = 1; i <= dt.Rows.Count; i++)
{
rg[1, i] = dt.Rows[i - 1][0].ToString(); //For Adding Header Text
rg[2, i] = int.Parse(dt.Rows[i - 1][1].ToString()); //For Adding Datarow Value
}
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, Type.Missing);
xlChart.ChartType = Excel.XlChartType.xlLine;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = "Project Status Graph";
// *****************Set legend:***************************
xlChart.HasLegend = true;
//FileStream file = new FileStream(#"d:\pop.xls", FileMode.Create);
//file.Close();
wb.SaveCopyAs(#"d:\pop.xls");
// ****************For Quiting The Excel Aplication ***********************
if (xla != null)
{
xla.DisplayAlerts = false;
wb.Close();
wb = null;
xla.Quit();
xla = null;
}
}
private System.Data.DataTable GetGraphData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("ProjectStatus"), new DataColumn("per") });
DataRow dr1 = dt.NewRow();
dr1[0] = "Compleet";
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Pending";
dr2[1] = 20;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "UnCompleet";
dr3[1] = 20;
dt.Rows.Add(dr3);
return dt;
}
i guess these below line are not fine.
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
this way i solved
this is just a sample code not real life implementation
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel;
using System.IO;
namespace WindowsForms_chartexcel
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";
xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";
xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";
xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";
xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";
Excel.Range chartRange ;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(200, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "d5");
chartPage.SetSourceData(chartRange, misValue);
//chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.ChartType = Excel.XlChartType.xlLine;
if (File.Exists(#"d:\test.xls"))
{
File.Delete(#"d:\test.xls");
}
xlWorkBook.SaveAs(#"d:\test.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file d:\test.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}

written code for Autofit in c# for Excel sheet. Everything is perfect. but the Excel.exe is still running even after clearing com componets

This is my code. I am trying to export gridview to excel with some of the cells with color and autofit. The problem here is everything is working fine except the EXCEL.EXE running in the background. But If i exclude code for Autofit and coloring cells, then the Excel Task is terminated.
Below is my code
protected void xlsWorkBook()
{
try
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Workbooks oWBs;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWBs = oXL.Workbooks;
oWB = oWBs.Add(1);
oSheet = oWB.ActiveSheet;
DataGridView dataGridExport = new DataGridView();
dataGridExport.DataSource = GetData();
bool isColorCells = false;
oRange = oSheet.Cells;
for (int k = 1; k <= dataGridExport.Columns.Count; k++)
{
//oRange.set_Item(1, k, dataGridExport.Columns[k - 1].Name);
oSheet.Cells[1, k] = dataGridExport.Columns[k - 1].Name;
((dynamic)oSheet.Cells[1, k]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SteelBlue);
}
for (int i = 1; i <= dataGridExport.Rows.Count; i++)
{
for (int k = 1; k <= dataGridExport.Rows[i - 1].Cells.Count; k++)
{
if (Convert.ToString(dataGridExport.Rows[i - 1].Cells[k - 1].Value) != string.Empty)
{
//oRange.set_Item(i + 1, k, dataGridExport.Rows[i - 1].Cells[k - 1].Value);
oSheet.Cells[i + 1, k] = dataGridExport.Rows[i - 1].Cells[k - 1].Value;
}
if ((isColorCells) && (dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb() != 0))
{
//oRange.Interior.Color = Color.Red;
((dynamic)oSheet.Cells[i + 1, k]).Interior.Color = ColorTranslator.ToOle(Color.FromArgb(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb()));
}
}
}
dataGridExport = null;
oSheet.Columns.AutoFit();
//oRange.EntireColumn.AutoFit();
// Save the sheet and close
//oSheet = null;
//oRange = null;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xlsx";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
oWB.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
}
GC.Collect();
GC.WaitForPendingFinalizers();
oWB.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRange);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWBs);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
this.Cursor = Cursors.Default;
}
Moving Range to different function solved my problem. The Excel.exe is not running at the background anymore. But i am not sure why. Somebody can give explanation for this?
protected void xlsWorkBook()
{
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
//oXL.Visible = false;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
UpdataDataToExcelSheets(oSheet,"sheet name",dataGrid1,true);
// Save the sheet and close
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xlsx";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
oWB.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
}
oWB.Close();
oXL.Quit();
//// Clean up
if (oSheet != null)
{
Marshal.FinalReleaseComObject(oSheet);
oSheet = null;
}
if (oWB != null)
{
Marshal.FinalReleaseComObject(oWB);
oWB = null;
}
if (oXL.Workbooks != null)
{
Marshal.FinalReleaseComObject(oXL.Workbooks);
}
if (oXL != null)
{
Marshal.FinalReleaseComObject(oXL);
oXL = null;
}
//// NOTE: When in release mode, this does the trick
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void UpdataDataToExcelSheets(Excel.Worksheet oSheet,string sheetName, DataGridView dataGridExport,bool isColorCells)
{
Excel.Range oRange;
oSheet.Name = sheetName;
for (int k = 1; k <= dataGridExport.Columns.Count; k++)
{
oSheet.Cells[1, k] = dataGridExport.Columns[k - 1].Name;
((dynamic)oSheet.Cells[1, k]).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.SteelBlue);
}
for (int i = 1; i <= dataGridExport.Rows.Count; i++)
{
for (int k = 1; k <= dataGridExport.Rows[i - 1].Cells.Count; k++)
{
if (Convert.ToString(dataGridExport.Rows[i - 1].Cells[k - 1].Value) != string.Empty)
{
oSheet.Cells[i + 1, k] = dataGridExport.Rows[i - 1].Cells[k - 1].Value;
}
if ((isColorCells)&&(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb() != 0))
{
((dynamic)oSheet.Cells[i + 1, k]).Interior.Color = ColorTranslator.ToOle(Color.FromArgb(dataGridExport.Rows[i - 1].Cells[k - 1].Style.BackColor.ToArgb()));
}
}
}
oRange = oSheet.Range[oSheet.Cells[1, 1],
oSheet.Cells[dataGridExport.Rows.Count - 1, dataGridExport.Columns.Count + 1]];
oRange.EntireColumn.AutoFit();
if (oRange != null)
{
Marshal.FinalReleaseComObject(oRange);
oRange = null;
}
}

Categories

Resources