Excel Interop - Set filename before saving - c#

Is it possible to set the excel filename before file saving?
I have following simple code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Excel.Workbook workbook = excel.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet sheet = workbook.Sheets[1];
sheet.Cells[1, 1] = "Hello World!";
Is it possible to predefine this name before saving?
Thanks.

There is no explicit, foolproof way to do this prior to saving, unfortunately. The closest you could come is to use a template. If you have a template called FOO.xltx, you could create your workbook like this:
Application.Workbooks.Add "X:\path\to\FOO.xltx"
The only quirk is that the name for the new documents will be appended with an incrementing number (FOO1 the first time, then FOO2,FOO3, etc.).
To create a template, just create a new document, and when you save it, select Excel Template (*.xltx) from the Save as type dropdown.

You have to use saveas to save the file with the filename you want. Then when the user clicks save it will just update the file that was previously created. Unfortunately there is no other way. Here is the code:
workbook.SaveAs(Filename: FILENAMEHERE);
Here is the MSDN doc for it: https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.saveas.aspx

Related

How to work with excel file in memory

at the moment my current process is as followed. Query database - > Save file locally -> Open Workbook using Excel Interop Dll, Make Changes To Work Book, Save As using Excel Interop Dll. The reason for save as is because I require some addition settings so the file isn't set to read only.
The issue I'm coming across is that it's saving locally twice. First time is fine, second time a prompt will appear asking if I would like to override. I'm wondering how can I remove the Save File Locally process and have it in memory to work with? If I am able to work with the file in memory, I would have the prompt on Save As asking me if I would like to override the previous file.
Code:
//Save File Locally
System.IO.File.WriteAllBytes(saveFileDialog.FileName, Report.FileArray);
var fileLocation = saveFileDialog.InitialDirectory + saveFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
// Open Workbook Using Excel Interop Dll
Workbook wb = excel.Workbooks.Open(fileLocation);
Worksheet ws1 = wb.Worksheets.get_Item("English");
//Make Changes To WorkBook
ws1.Range["E5"].Value = StartDate;
ws1.Range["G5"].Value = EndDate;
// Save AS Using Excel Interop With shared settings to remove read only access
wb.SaveAs(fileLocation, AccessMode: XlSaveAsAccessMode.xlShared);
Process.Start(fileLocation);
You'd better disable the prompt, to what I remember this is possible but it imply a lot of umnaged code...
Try this
Microsoft.Office.Interop.MSProject.Application msProjectApp = new Microsoft.Office.Interop.MSProject.Application();
msProjectApp.DisplayAlerts = false;
Edit
Microsoft.Office.Interop.Excel.Application msProjectApp = new Microsoft.Office.Interop.Excel.Application();
msProjectApp.Visible = true; //show the application and not need to start a process
msProjectApp.DisplayAlerts = false;
//Save File Locally
System.IO.File.WriteAllBytes(saveFileDialog.FileName, Report.FileArray);
var fileLocation = saveFileDialog.InitialDirectory + saveFileDialog.FileName;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
// Open Workbook Using Excel Interop Dll
Workbook wb = excel.Workbooks.Open(fileLocation);
Worksheet ws1 = wb.Worksheets.get_Item("English");
//Make Changes To WorkBook
ws1.Range["E5"].Value = StartDate;
ws1.Range["G5"].Value = EndDate;
// Save Only
wb.Save();
Remove Process.Start
excel.Visible = true;
excel.DisplayAlerts = false;
If you "own" the workbook and can set it up beforehand to play nice and are only loading in data, I find the OleDB Access SQL connection approach to be a better way to load raw data into SQL.

Worksheet.SaveAs Method Saves All Sheets

Using C# to write a method that takes a single worksheet out of a workbook and saves it as HTML.
I am using the Worksheet.SaveAs method as described on MSDN.
However, when I look at the output it has gone and saved all of the worksheets within the workbook, not just the one I selected. It's as though Worksheet.SaveAs and Workbook.SaveAs just do the same thing.
Simplified code:
public static void saveSingleSheetAsHTML(string workbook, string destination, string sheetName)
{
Application excel = new Application();
excel.Workbooks.Open(Filename: workbook);
Microsoft.Office.Interop.Excel._Worksheet worksheet = excel.Worksheets[sheetName];
var format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
worksheet.SaveAs(destination, format);
}
Now when I open the resulting HTML file it has only gone and exported the entire workbook, not the sheet.
As said by Tim Williams in a comment I found after hitting a link posted by I love my monkey above:
"You cannot call SaveAs on a worksheet - first call .Copy to create a
standalone new workbook containing only that sheet, then save that
workbook."
No idea why you cannot. The docs on MSDN do not give any clue about this and suggest it should be possible.
So having created a new workbook:
var newbook = excel.Workbooks.Add(1);
Copy the sheet over, which will place it as the first sheet:
excelWorksheet.Copy(newbook.Sheets[1]);
Then delete the default "Sheet1", which will always be the 2nd sheet:
newbook.Worksheets[2].Delete();
Then call the SaveAs method and then close the new book:
newbook.SaveAs(Filename: destination, FileFormat: format);
newbook.Close();
This did save the new workbook as HTML, but also put the tabs at the bottom, which I was hoping to avoid as there is only 1 tab now. It does meet my minimum needs, though I would like to figure out how to make it a bit neater.

How can I read an Excel 2010 file in my C# code using a DLL?

UPDATE1:
I am using Excel 2010 and I've searched the web and found thousands upon thousands of ways to do this via win form, console, etc. But I can't find a way to do this via DLL. and none of the sample on-line is complete all in bit and pieces.
UPDATE END
I have looked and goggled but did not get the specific what i am looking for, as show below the excel sample sheet.
i'm looking a way to read and store the each cell data in a variable
i have started something like this:
Workbook workbook = open(#"C:\tmp\MyWorkbook.xls");
IWorksheet worksheet = workbook.Worksheets[0];
IRange a1 = worksheet.Cells["A1"];
object rawValue = a1.Value;
string formattedText = a1.Text;
Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);
Your code can work with a couple changes.
One thing to remember is that Excel worksheets are 1-based, not 0-based (and use Worksheet instead of IWorksheet):
Worksheet worksheet = workbook.Worksheets[1];
And to get a range, it is easiest to call get_Range() on the worksheet object (and use Range instead of IRange):
Range a1 = worksheet.get_Range("A1");
With those two lines of code changed, your example will work fine.
UPDATE
Here is a "complete" example:
Right-click your project in the solution explorer and click "Add
Reference".
Click on the COM tab and sort the list by Component Name. Find "Microsoft Excel 14.0 Object Library" in the list and select it. Click OK.
In the code file where you want this to run, add a using Microsoft.Office.Interop.Excel;
Use this code, which I've modified as little as possible from your example:
var excel = new Microsoft.Office.Interop.Excel.Application();
Workbook workbook = excel.Workbooks.Open(#"C:\tmp\MyWorkbook.xls");
Worksheet worksheet = workbook.Worksheets[1];
Range a1 = worksheet.get_Range("A1");
object rawValue = a1.Value;
string formattedText = a1.Text;
Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);
Excel.Sheets sheets = workbook.Worksheets;
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
System.Array myvalues;
Excel.Range range = worksheet.get_Range("A1", "E1".ToString());
myvalues = (System.Array)range.Cells.Value;
If you don't want to be in a war with com components and registering dlls,
the best way to read excel is Excel Reader for .NET
I have been using it for so long time , and I can say it just works.
and excelReader.IsFirstRowAsColumnNames property makes everything easy.
You can play your data within a dataset.

Pass parameters to VSTO-enabled Excel Spreadsheet on server

I created an Excel 2010 Workbook project with to customize some ribbon extensions. It uses a webservice to read in data to pre-populate the form. My question is, how can I pass in some parameters, for example a record ID, to the workbook when it is requested from the server?
I think my scenario is similar to this question, which was never answered: Pass Data into a VSTO Excel Workbook?
There is a way of passing data to a workbook which personally I don't really like, but maybe it can suit you. Basically, you set values for specific cells in the workbook, and then process those values in Excel's event handler:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = excel.Workbooks.Open(filepath);
var sheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
var range = sheet.Range["A1"];
range.Value2 = "some value";

Save Entire Workbook as PDF Excel 2010 (C#)

Is there anyway to save you entire workbook as a pdf in excel. I found this, http://msdn.microsoft.com/en-us/library/bb407651(v=office.12).aspx, but it does not exactly tell you if it saves the entire workbook as a pdf or just the active sheet. If there is no way to save the entire workbook to pdf, would printing the entire workbook be the best option, or even possible in C#? Below is what I have thus far I just need it to save as pdf so I can send in an email. Thanks for the help.
using Excel = Microsoft.Office.Interop.Excel; //Excel Reference
//Gets Excel and gets Activeworkbook and worksheet
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
//Create New Instance in Excel
oXL = new Excel.Application();
oXL.Visible = true;
//Open Excel Workbook
oWB = oXL.Workbooks.Open("");
oWB = (Excel.Workbook)oXL.ActiveWorkbook;
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
//Modify Excel Spreadsheet Based on Form
oSheet.Cells[6, 4] = maskedTextBox1.Text; //Change Value in Cell, Cell Location [y-axis, x-axis]
//Save Workbook As
oWB.SaveAs("");
//Save Workbook As PDF
//Close Workbook
oWB.Close("");
//Quit Excel
oXL.Quit();
In 2010 you can save the entire workbook in PDF by making each sheet an "Active" sheet.
Sounds strange but if you notice the print options when you do a pdf there is no option for workbook. To get around this open an excel file and fill in some data in 2-3 work sheets. Now hold your ctrl key and click on each other workbook, it will then become a "Group".
You will notice the [GROUP] name appear at the top of the excel file and now when you print the excel file it will print the entire workbook.
Try this out for yourself. In code, you just need to make each work sheet an active worksheet. I don't work much with the excel object model but it might be worth doing a macro for this and looking at the code.
I recorded a macro and here is the VBA:
Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
Looks as though you just need to store each sheet in an array and then simply
Sheets(MyArray).Select
This will then make all sheets active and [grouped] and then you can run a print out to pdf. By recording the macro it also presented the options to print to pdf:
`ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\MyAccount\Desktop\test.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True`
In this case active sheet is your group of sheets that you have stored in an array.

Categories