Print Specific worksheet in Excel - c#

I have a c# function that prints an excel file from it's path. The excel file contains multiple worksheet and I want to be able to select which worksheet to print
private void PrintExcelDocument()
{
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "print",
FileName = Path,
UseShellExecute = true,
CreateNoWindow = true
};
process.Start();
// Fermer le processus s'il est encore ouvert
if (!process.HasExited)
{
process.WaitForExit(5000);
}
process.Close();
}
How can I specify if I want to print all worksheets or one specific ? At the moment, it prints the last one that was opened (when I last saved the file).
I tried adding Arguments with the workbook name but no luck. Also, I haven't found any documentation regarding Excel printing from process. I know I can use Microsoft's dll for Excel (Microsoft.Office.Interop.Excel) but I would like to avoid it if possible.

If you do not like to use Excel Interop COM then this might be helpful to you considering that you are working with .xlsx file format.
If you open an excel file with Hex-editor you will notice that the file signature is PK(zip file format), meaning that it is basically zipped XML files.
Thus, you can just right click the excel.xlsx file, unzip it and then inside '\xl\worksheets' folder you will see 'sheet[1~10].xml' files
Now use the following codes to get all the worksheets
using System.IO;
string[] file_arr = Directory.GetFiles(#"C:\path\to\files\", "*.xlsx");

Related

Can't open bound excel file in C# project

I have an excel file in my project which is listed as resource.
Now I try to open it with a button click like this:
private void Button_Click_Blist(object sender, RoutedEventArgs e)
{
Excel.Application xl = new Excel.Application();
Excel.Workbook wb = xl.Workbooks.Open("Blist.xlsx");
}
My problem is that it says that it can't find the file and throws this exception:
System.Runtime.InteropServices.COMException
We couldn't find 'Blist.xlsx'. Was the object perhaps moved, renamed,
or deleted?
This code uses OLE Automation to start Excel and tell it to open a file in the relative path Blist.xlsx. The executable in this case is Excel, not your own application. The relative path will be resolved using Excel's working directory.
To avoid this problem, pass the absolute file path to Excel :
var fullPath=Path.GetFullPath("Blist.xlsx");
Excel.Workbook wb = xl.Workbooks.Open(fullPath);
Another possibility, which gives no control of (or dependency on) Excel, is to just "start" the file with Process.Start, eg :
Process.Start("Blist.xlsx");
Or
var fullPath=Path.GetFullPath("Blist.xlsx");
Process.Start(fullPath);
The Windows Shell will find the application that can open this document based on its extension and start it, passing the file path as an argument. This can start Excel, Libre Calc or any other application registered to open this particular file extension.
So I tried this and apparently the .Open() method some extra complexety with relative paths (see #PanagiotisKanavos comment). You can make a work around, by getting the current directory path, and pre-pending it, giving the absolute path of the file:
string filename = "Blist.xlsx";
string currentPath = Directory.GetCurrentDirectory();
var xl = new Microsoft.Office.Interop.Excel.Application();
var wb = xl.Workbooks.Open(currentPath + "\\" + filename);
xl.Visible = true;
However, you should (almost) never use hardcoded file names in your code. So the above solution is just an example, not something to copy into production code...

Open Excel with password in C#, and close the excel externally

I am looking for a way to open the password protected Excel file in Excel from my c# program.
Please notice I just need to open it for my user. I am not looking for something like Excel Interop to modify the file.
For a file that has no password, I can simply launch the process start with the full path file name as a parameter. But this one has password in it, so it can't be done like this.
If I use Excel interope to open it, I can open it, but the Excel process will leave there when user close the Excel window.
var excelApp = new Excel.Application();
excelApp.Visible = true;
var wb = excelApp.Workbooks.Open(#"d:\temp\test.xlsx", Password:"1234");
Since user will be modifying the file in the Excel window and then close the windows. This part is out of my control. I simply just want to launch the file, then I don't have to care about it. But by using Excel interope, the COM is actually referecing back to my c# program, so that the whole Excel process can't be disposed completely.
I think I know a workaround for it.
Create a helper C# console application called OpenExcelWorkbookWithPassword.exe which looks like that:
static void Main(string[] args)
{
var excelapp = new Excel.Application();
excelapp.Visible = true;
Excel.Workbook workbook = excelapp.Workbooks.Open(args[0], Password: args[1]);
}
and use this from your main application with the following code:
string path = #"d:\temp\test.xlsx";
string pw = "1234";
System.Diagnostics.Process.Start("OpenExcelWorkbookWithPassword.exe", path + " " + pw);
When the user is closing Excel the Excel.exe process will be terminated even if your main application is still running.

How can I save an .xlsx file as Unicode text using interop?

I have to build a report making desktop application . I need it to be really user friendly, the reports are in Hebrew so it has to be Unicode and not just a regular .csv file or I get question marks.. I want to receive the file path of the report (like c:\folder\file.xlsx) and be able to save a copy of the original file in another location as a Unicode text file.. Help?
Same problem as this guy.
"I need to use the saveas() from Microsoft.office.interop.excel but I can't figure how to do it "
Add this:
using Excel = Microsoft.Office.Interop.Excel;
Then use this code:
Excel.Application app = new Excel.Application();
try
{
app.DisplayAlerts = false;
app.Visible = false;
Excel.Workbook book = app.Workbooks.Open("D:\\test.xlsx");
book.SaveAs(Filename: "D:\\test.txt", FileFormat: Excel.XlFileFormat.xlUnicodeText,
AccessMode: Excel.XlSaveAsAccessMode.xlNoChange,
ConflictResolution: Excel.XlSaveConflictResolution.xlLocalSessionChanges);
}
finally
{
app.Quit();
}
"D:\\test.xlsx" is your input excel filename and "D:\\test.txt" is your unicode text output filename.

How to change the default program to open any Word documents, using C#?

In my WPF application, I want to open Word documents in Word 2007 or above, whether or not the default program for opening Word documents is Word 2007. Even if the default program to open Word documents is Open Office, I want to open them in Word 2007+.
How can I do this?
This doesn't really have anything to do with WPF.
You'll need to now where Word is installed or add the the folder in which it is located to the Path environment variable.
Assuming your file name variable is called fileName and the full path of winword.exe is stored in wordPath (or winword.exe is in the Path), you would need to do something like this -
ProcessStartInfo startInfo = new ProcessStartInfo
{
CreateNoWindow = false,
Arguments = fileName,
FileName = wordPath
};
Process wordProcess = Process.Start(startInfo);
Note 1 - your fileName is passed directly to Word. If the path contains white spaces you'll have to wrap it in "". Something like
fileName = String.Format("{0}{1}{2}",
fileName.StartsWith("\"") ? "" : "\"",
fileName,
fileName.EndsWith("\"") ? "" : "\"");
Note 2 - Word has other command line arguments for different purposes, for other uses see here http://support.microsoft.com/kb/210565.

C# After I save a .csv in Excel, how do I open it?

I did a little research, and an unsure if I should be using
the Microsoft.Office.Interop.Excel
Just to clarify with the example: I'm taking a .txt, and doing stuff, then saving it as a .CSV (Comma Separated Values). I want to then open it (on button click or something...)
How can this be done?
Pair to your comment:
I want it to open in Excel.exe. It should be a separate window that launches after my program is done with its conversion
Simply start it using System.Diagnostics.Process class:
using System.Diagnostics.Process;//at top of your application
//
//At button click or after you finish editing
//
Process excel = new Process();
//if the excel was installed in the target machine and the default program to open csvs
//then you can simply just call process start and put the file path, like:
excel.Start(#"Your edited csv file path");
//otherwise:
excel.StartInfo.FileName = #"The excel application file path";
excel.StartInfo.Arguments = #"Your edited csv file path";
excel.Start();
You can start the excel process with the file path as command line parameter (excel.exe C:\myFile.csv). This will open it in excel.
Yup, Microsoft.Office.Interop.Excel is what you will need to open the CSV file in Excel.
Depends on which framework you are using (i.e. Silverlight or Windows Forms).
If I were you I'd be using OpenFileDialog to read the values from the comma seperated list into a string or a class. The sample below is for silverlight.
private void bOpenFileDialog_Click(object sender, RoutedEventArgs e)
{
// Create an instance of the open file dialog box.
var openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Filter = "CSV File (.csv)|*.csv|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
bool? userClickedOK = openFileDialog1.ShowDialog();
// Process input if the user clicked OK.
if (userClickedOK == true)
{
// Open the selected file to read.
System.IO.Stream fileStream = openFileDialog1.File.OpenRead();
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
{
// Read the first line from the file and write it the textbox.
tbResults.Text = reader.ReadLine();
//the results of your CSV are now stored in tbResults.Text
//optionally you could parse the .CSV using string.Spit(',') into a string array
}
fileStream.Close();
}
}
Is this a WinForms, WPF, or ASP.NET application? If you use the Office Interop libraries you are dependent on Office being installed on that machine. If it's a web server, you don't want to run Excel that way.
Check out www.SpreadSheetGear.com. No affiliation, just very satisfied.

Categories

Resources