Close Excel in C# after the saving the file - c#

I am using C# to write some information to an Excel file:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Globalization;
public void OpenExcel(string folder, string filename)
{
this.folder = folder;
this.filename = filename;
path = folder + #"\" + filename;
if (File.Exists(path) != true) //if the output file does not exists, create it
{
var app = new Microsoft.Office.Interop.Excel.Application();
var temp = app.Workbooks.Add();
temp.SaveAs(path);
temp.Close();
}
wb = excel.Workbooks.Open(path);
}
After I am done and have saved the file, I want to close it:
public void Close()
{
wb.Close(false);
excel.Quit();
excel.Application.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
workSheet = null;
wb = null;
excel = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
Both of the voids above are part of a class object named ExcelFile. However, when I use the code above and exit the program I have made, Excel still is left as a background process like in this question: C# closing Excel after using
I have seen that there are a few threads on stackoverflow on this topic, but no solution seems to work for me. I want to avoid killing all Excel processes if possible since this is a program that will make calculations using thread pool that will take hours to make.

Related

Issue when open/save excel files with C#

I am trying to access excel modules with C# and I am having trouble after saving the excel file.
There are duplicate Thisworkbook and Sheets appearing as the picture below.
This only happens when the excel file has Modules while everything will be fine if the excel has only sheets in the project.
Here is the code which is nothing but only opening and saving the same file.
I am using WIN10/ VS2013 /EXCEL 2010.
Does anyone know why will this happen?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Vbe.Interop;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\test.xls";
Excel._Application app = new Excel.Application();
Excel._Workbook workbook = app.Workbooks.Open(filepath);
workbook.SaveAs(filepath);
workbook.Close(true);
app.Quit();
}
}
}

Get the path of the file that launched my app

I'm working in my own PDF Reader using C# & Patagames/PDFium library and I am able to open files using "OpenFileDialog" and show them on the screen. However, due requirements of the boss I am not allowed to have any buttons in the screen. All we want is to click the any .PDF file (For example, in this route: C:\Users\Adaptabilidad\Desktop\Test.pdf) and launch it & show the PDF document directly, without looking for the directory of the file. I've set my ".exe" as default app, although, the PDF Reader is executed no PDF file is displayed.
I've tried Application.ExecutablePath, Application.StartUpPath after initializing the component and I'm still getting the route of my PDF reader executable (.Exe) but I need to know what the file to be open is (filepath).
How can I get the information about the .pdf file (directory can vary) that is launching my app? You can see my code below if helps.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Patagames;
using System.IO;
namespace aPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "PDF Files (*.pdf)|*.pdf";
if (dialog.ShowDialog() == DialogResult.OK)
{
openfile(dialog.FileName);
}
}
public void openfile(string filepath)
{
byte[] bytes = System.IO.File.ReadAllBytes(filepath);
var stream = new MemoryStream(bytes);
Patagames.Pdf.Net.PdfDocument pdfDocument = Patagames.Pdf.Net.PdfDocument.Load(stream);
pdfViewer1.Document = pdfDocument;
}
}
}
Updates:
I've found a way. One of you guys that commented allowed me to find out how to do it.
What I used is the following sentence in my Program.cs:
public static string[] cmdLine = Environment.GetCommandLineArgs();
public static string cmd = cmdLine[1];
Then, y use "cmd" as filepath.
Why? Environment.GetCommandLineArgs(); returns 2 values, the .exe you're executing (your program) & as second value the file that you've used in order to launch that .exe.
That's it. Thank you for your answers.

How to copy an excel sheet from workbook A to workbook B

I have the below code to copy Sheet1 from a workbook (test1.xlsx) to another workbook (test2.xlsx). The code doesn't have any errors and it takes forever to execute and I had to stop the code with no change in the files. Please let me know what is wrong.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace Read_from_Excel_file
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook test1 = xlApp.Workbooks.Open(#"C:\Users\namokhtar\Desktop\test1.xlsx");
Excel.Workbook test2 = xlApp.Workbooks.Open(#"C:\Users\namokhtar\Desktop\test2.xlsx");
test2.Worksheets.Copy(test1.Worksheets["Sheet1"]);
test2.Save();
test1.Close();
test2.Close();
xlApp.Quit();
}
}
}
I think you need to specify where to copy the worksheet to. So at line
test2.Worksheets.Copy(test1.Worksheets["Sheet1"]);
you have to specify which worksheet in test2 you want to copy the worksheet in. test2.Worksheets["whateverworksheetyouwanttooverwrite"].Copy(test1.Worksheets["Sheet1"]);
Source: (https://learn.microsoft.com/nl-nl/visualstudio/vsto/how-to-programmatically-copy-worksheets?view=vs-2017)

Enable to read cell value from Excel to C# while

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
namespace EXCEL_SMS
{
class Program
{
static void Main(string[] args)
{
string path = "C:\\Projects\\ExcelSingleValue\\Test.xlsx ";
Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.Activesheet;
// Read the first cell
string test = excelSheet.Cells[1, 1].Value.ToString();
// string sValue = (range.Cells[2, 4] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
wb.Close();
}
}
}
I am getting error at activesheet, I want read cell value from Excel while it's open. Can anyone tell how I can achieve it? I'm using Visual Studio 2012.
there is a mistake in "ActiveSheet" please correct it will work fine, in your code it is "Activesheet" ('s' is a small need to be Capital 'S')
Worksheet excelSheet = wb.ActiveSheet; //wb.Activesheet;
Please see the result I am getting with the same program as below, I am able to get the first Cell from test.xlsx

write to memoerystream using epplus

I have this assembly that basically creates an empty excel file using EPPLUS library. The file is created directly to desk, but i want first to write it in a memoerystream and then save the memoerystream to desk. I have this so far.
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplicationXLSX
{
class Program
{
static void Main(string[] args)
{
Createxlsx("XLSX");
}
public static void Createxlsx(string filename)
{
FileInfo newFile = new FileInfo("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx");
MemoryStream ms = new MemoryStream();
//create a package
using (ExcelPackage package = new ExcelPackage(ms))
{
package.Workbook.Worksheets.Add("worksheet");
package.Save();
}
}
}
}
Try
package.SaveAs(ms)
That should fill your stream with the excelfile-content.

Categories

Resources