473,471 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Excel Interop - How to prompt the user to save the file?

4 New Member
Hi guys i have an invoicing application (c#) that creates an excel workbook. At the moment i am using:

Expand|Select|Wrap|Line Numbers
  1. oWB.SaveAs("D:\\" + strFile, Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, null, null, null);
This automatically saves to my D:\ (still testing the application).

Any ideas?
Aug 7 '09 #1
11 20388
tlhintoq
3,525 Recognized Expert Specialist
Use a "SaveFileDialog"
Aug 7 '09 #2
mcam9
4 New Member
@tlhintoq
How do incorporate that into my code above?
Aug 7 '09 #3
tlhintoq
3,525 Recognized Expert Specialist
@mcam9
You've only provided one line of code so I can't exactly tell where to insert...
  • Make a new SaveFileDialog
  • Show it
  • Get the path returned from it
  • Use that path as the new save path, in place of your hard coded "D:\" + FileName
Aug 7 '09 #4
mcam9
4 New Member
Here is my code:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Web;
  7. using System.Web.SessionState;
  8. using System.Web.UI;
  9. using System.Web.UI.WebControls;
  10. using System.Web.UI.HtmlControls;
  11. using System.Diagnostics;
  12. using System.Reflection;
  13. using Excel; //= Microsoft.Office.Interop.Excel;
  14. using System.Data.SqlClient;
  15. using System.IO;
  16. using System.Text;
  17. //using System.Collections;
  18. using System.Collections.Generic;
  19.  
  20.  
  21.  
  22.  
  23. namespace ANINVWebApp.BusinessLayer
  24. {
  25.     public class CreateExcel
  26.     {
  27.  
  28.  
  29.  
  30.  
  31.         public static void CreateXL(Guid ID, String NTID)
  32.         {
  33.             Excel.Application oXL = null;
  34.             Excel._Workbook oWB = null;
  35.             Excel._Worksheet oSheet = null;
  36.             //Excel.Sheets NewSheet = null;
  37.             Excel.Range oRng = null;
  38.             oXL = new Excel.Application();
  39.             oXL.Visible = false;
  40.             string fromDate = "";
  41.             string toDate = "";
  42.             string invoiceNo = "";
  43.             string foreName = "";
  44.             string surName = "";
  45.             string phone = "";
  46.             oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
  47.             List<BillingPlanDA> dates = new List<BillingPlanDA>();
  48.             dates = BillingPlan.GetBillingDates(ID);
  49.             foreach (BillingPlanDA rec in dates)
  50.             {
  51.                 fromDate = rec.BillingFrom.ToString("MMM dd, yyyy");
  52.                 toDate = rec.BillingTo.ToString("MMM dd, yyyy");
  53.                 invoiceNo = rec.InvoiceNumber.ToString();
  54.  
  55.             }
  56.  
  57.             List<ProjectInvoiceDA> manager = new List<ProjectInvoiceDA>();
  58.             manager = ProjectInvoice.GetManager(NTID);
  59.             foreach (ProjectInvoiceDA detail in manager)
  60.             {
  61.                 foreName = detail.Forename.ToString();
  62.                 surName = detail.Surname.ToString();
  63.                 phone = detail.Telephone.ToString();
  64.  
  65.  
  66.             }
  67.  
  68.  
  69.  
  70.             List<ProjectInvoiceDA> proj = new List<ProjectInvoiceDA>();
  71.             proj = ProjectInvoice.GetProjectInvoices(ID, NTID);
  72.             int counter2 = 1;
  73.  
  74.             foreach (ProjectInvoiceDA rec in proj)
  75.             {
  76.  
  77.  
  78.                 List<EmployeeInvoiceDA> records = new List<EmployeeInvoiceDA>();
  79.                 records = EmployeeInvoice.GetEmployeeInvoices(rec.ProjectInvoiceId);
  80.                 string ProjCode = rec.ProjectCode.ToString();
  81.                 string TeamName = "";
  82.                 string CostCenter = rec.CostCenter.ToString();
  83.  
  84.  
  85.  
  86.  
  87.  
  88.                 try
  89.                 {
  90.                     GC.Collect();// clean up any other excel guys hangin' around...
  91.                     //Get a new workbook.
  92.  
  93.                     oWB.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
  94.                     oSheet = (Excel._Worksheet)oWB.ActiveSheet;
  95.  
  96.  
  97.                     string strConnect = System.Configuration.ConfigurationManager.AppSettings["connectString"];
  98.  
  99.                     oSheet.get_Range("A1", "Z3").Font.Bold = true;
  100.                     oSheet.get_Range("A16", "L16").Font.Bold = true;
  101.  
  102.  
  103.  
  104.  
  105.  
  106.                     //oSheet.get_Range("A1", "A2").C
  107.                     oRng = oSheet.get_Range("A4", "J4");
  108.                     oRng.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = Excel.Constants.xlSolid;
  109.                     oRng = oSheet.get_Range("A14", "J14");
  110.                     oRng.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = Excel.Constants.xlSolid;
  111.                     oRng.Borders[XlBordersIndex.xlEdgeTop].LineStyle = Excel.Constants.xlSolid;
  112.  
  113.  
  114.                     oSheet.Cells[7, 8] = "Invoice Number:";
  115.                     oSheet.Cells[7, 10] = invoiceNo;
  116.                     oSheet.Cells[8, 8] = "Invoice Date:";
  117.                     oSheet.Cells[8, 10] = toDate;
  118.                     oSheet.Cells[10, 8] = "Project Number: ";
  119.                     oSheet.Cells[10, 10] = ProjCode;
  120.                     oSheet.Cells[14, 1] = "For services rendered between " + fromDate + " - " + toDate;
  121.                     oSheet.Cells[16, 1] = "PO";
  122.                     oSheet.Cells[16, 2] = "Service No";
  123.                     oSheet.Cells[16, 3] = "Grade";
  124.                     oSheet.Cells[16, 4] = "Employee Name";
  125.                     oSheet.Cells[16, 5] = "Cost Center";
  126.                     oSheet.Cells[16, 6] = "Internal Order #";
  127.  
  128.                     oSheet.Cells[16, 7] = "Project #";
  129.                     oSheet.Cells[16, 8] = "Hours";
  130.                     oSheet.Cells[16, 9] = "Rate";
  131.                     oSheet.Cells[16, 10] = "Total Due";
  132.  
  133.                     int counter = 17;
  134.                     double total = 0;
  135.                     double hours = 0;
  136.                     foreach (EmployeeInvoiceDA record in records)
  137.                     {
  138.  
  139.  
  140.                         oSheet.Cells[counter, 1] = record.PO.ToString();
  141.                         oSheet.Cells[counter, 2] = record.ServiceNo.ToString();
  142.                         oSheet.Cells[counter, 3] = record.Grade.ToString();
  143.                         oSheet.Cells[counter, 4] = record.EmployeeName.ToString();
  144.                         oSheet.Cells[counter, 5] = CostCenter;
  145.                         oSheet.Cells[counter, 6] = "";
  146.                         oSheet.Cells[counter, 7] = record.ProjectNo.ToString();
  147.                         oSheet.Cells[counter, 8] = record.Hours.ToString();
  148.                         oSheet.Cells[counter, 9] = record.BillingRate.ToString("c");
  149.                         oSheet.Cells[counter, 10] = record.TotalDue.ToString("c");
  150.  
  151.                         hours = hours + Convert.ToDouble(record.Hours);
  152.                         total = total + Convert.ToDouble(record.TotalDue);
  153.                         TeamName = record.ProjectNo.ToString();
  154.                         counter++;
  155.  
  156.  
  157.  
  158.                     }
  159.                     string range = Convert.ToString(counter + 1);
  160.                     oRng = oSheet.get_Range("A" + range, "J" + range);
  161.                     oSheet.get_Range("A" + range, "J" + range).Font.Bold = true;
  162.                     oRng.Borders[XlBordersIndex.xlEdgeTop].LineStyle = Excel.Constants.xlSolid;
  163.                     oSheet.Cells[12, 1] = "Team Name:" + TeamName;
  164.                     oSheet.Cells[counter + 1, 1] = "VENDOR SUMMARY";
  165.                     oSheet.Cells[counter + 1, 5] = "Grand Total";
  166.                     oSheet.Cells[counter + 1, 8] = hours.ToString();
  167.                     oSheet.Cells[counter + 1, 10] = total.ToString("c");
  168.                     oSheet.get_Range("A" + counter+3 , "B" + counter + 3).Font.Bold = true;
  169.                                         oSheet.Name = rec.InvoiceHeading.ToString() + " " + ProjCode;
  170.                     oRng = oSheet.get_Range("A16", "J16");
  171.                     oRng.Font.Bold = true;
  172.                     oRng.Font.Underline = true;    
  173.  
  174.                     //oRng = oSheet.get_Range("A1", "Z1");
  175.                     //oRng.EntireColumn.AutoFit();
  176.                     oXL.Visible = false;
  177.                     oXL.UserControl = false;
  178.                     counter2++;
  179.  
  180.  
  181.                     GC.Collect();  // force final cleanup!
  182.  
  183.  
  184.                 }
  185.                 catch (Exception theException)
  186.                 {
  187.                     String errorMessage;
  188.                     errorMessage = "Error: ";
  189.                     errorMessage = String.Concat(errorMessage, theException.Message);
  190.                     errorMessage = String.Concat(errorMessage, " Line: ");
  191.                     errorMessage = String.Concat(errorMessage, theException.Source);
  192.                     //errLabel.Text = errorMessage;
  193.                 }
  194.             }
  195.  
  196.  
  197.             string strFile = "report" + System.DateTime.Now.Ticks.ToString() + ".xls";
  198.  
  199.             dlg.Filter = "Excel Worksheets|*.xls";
  200.  
  201.             //oWB.SaveAs(HttpContext.Current.Server.MapPath(".") + "\\" + strFile, Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
  202.             oWB.SaveAs("D:\\" + strFile, Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, null, null, null);
  203.             // Need all following code to clean up and extingush all references!!!
  204.  
  205.             oWB.Close(null, null, null);
  206.             oXL.Workbooks.Close();
  207.             oXL.Quit();
  208.             //System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
  209.             //System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
  210.             //System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
  211.             //System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
  212.             oSheet = null;
  213.             oWB = null;
  214.             oXL = null;
  215.  
  216.         }
  217.     }
  218. }
I have never used the Savefile dialog before. How does it know to save the excel file i have just create? Thanks for your patience, i am relatively new to .NET :)
Aug 7 '09 #5
tlhintoq
3,525 Recognized Expert Specialist
I'm a big believer in reading about new controls. Always best to actually understand how they work, than just shoehorn them in and hope for the best.
Here's the MSDN page for this control.

At around line 200 is where you will want to put in the SaveFileDialog
Make a new SaveFileDialog
Show it
Get the path returned from it
Use that path as the new save path, in place of your hard coded "D:\" + FileName
How does it know to save the excel file i have just create?
It doesn't. The dialog does not save your file. You already have that written. The Dialog presents a standard Save dialog box from which you can browse and receive the path and file name the user selected.

The best way to understand it is to use it... play with it... give it a try then let me know how it is treating you.
Aug 7 '09 #6
mcam9
4 New Member
What is the namespace for the savefiledialog i.e. using System.blah.blah. When i try to us

Expand|Select|Wrap|Line Numbers
  1.  SaveFileDialog DialogSave = new SaveFileDialog()
i get the error 'type or namespace name 'SaveFileDialog' could not be found (are you missing a using directive or an assembly reference'
Aug 11 '09 #7
GaryTexmo
1,501 Recognized Expert Top Contributor
System.Windows.Forms

It's kind of goofy how you don't get that information on the MSDN page... bleh.
Aug 11 '09 #8
tlhintoq
3,525 Recognized Expert Specialist
What is the namespace for the savefiledialog i.e. using System.blah.blah. When i try to us
Here's the MSDN page for this control.
It's kind of goofy how you don't get that information on the MSDN page... bleh.
Guys... Its right on the top of the MSDN page.

SaveFileDialog Class
Prompts the user to select a location for saving a file. This class cannot be inherited.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
Syntax
Please don't be offended when I point out this as a good example of making things tougher for yourself than necessary. Sometimes the best thing someone can do is walk away from the computer. Take a break even if you are behind schedule. Play with the dog. Take a walk. Put down the caffeine. When you come back to the computer move slower not faster. Take the time to actually read everything you are looking at instead of just skimming it for what look to be the important bits. In some situations an extra 30 seconds reading the entire page of the book, or the entire page on a site can save you 30 hours trying to figure something out that was already explained.
Aug 11 '09 #9
GaryTexmo
1,501 Recognized Expert Top Contributor
Funny, the top hit on google for "C# save file dialog" takes you to *this* page, which is where I was looking at and doesn't list the namespace. I didn't go to yours... but yes, there it is indeed.

You'd think Microsoft would be more consistent ;)
Aug 11 '09 #10
tlhintoq
3,525 Recognized Expert Specialist
@GaryTexmo
In at least 10 places on that page is a clickable link to the SaveFileDialog component.

The first paragraph for example:
How to: Save Files Using the SaveFileDialog Component
The SaveFileDialog component allows users to browse the file system and select files to be saved. The dialog box returns the path and name of the file the user has selected in the dialog box. However, you must write the code to actually write the files to disk.
TIP: Just hover over any of the links and look at their link address in the status bar of your web browser. Hovering over 'SaveFileDialog" link will show you the target of the link:
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.aspx
Which in this case even gives us the namespace because MS isn't really creative about their links.

Because you were in the MSDN area for Visual Studio 2008 (creating Windows Forms applications) there really isn't a need to tell you to use the System.Windows.Forms namespace. When you created a Windows Forms application the using statement would have been put into your Form automatically.

Google is a great tool and I use the living daylights out of it, but you have to take a moment and decide if it's top result is your top result.
Sometimes it pays to keep a folder of your own bookmarks in your browser. I find a good starting place to be the top of the System namespace. But that's just me.
Aug 11 '09 #11
GaryTexmo
1,501 Recognized Expert Top Contributor
Yes I know, but thank you anyway for your in depth explanation.

mcam9, if you have any more troubles, feel free to ask :)
Aug 11 '09 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: bob | last post by:
Im trying to figure out how to copy and paste cells in an excel spreadsheet using the Excel Interop. so far ive got... Microsoft.Office.Interop.Excel.Range wksRange; wksRange =...
4
by: SIVAKUMAR | last post by:
hi All, I had a requirement like, the web form should prompt for save when the user enters/modifies some data on the form and trying to go to other form by means of some Navigation.Then the web...
6
by: Mike | last post by:
can i open the save file dialog box from a asp.net web page? thx
4
by: Dries | last post by:
Hello, I am using Excel Interop to export data from a dataset to an excel-file. Everything works fine except closing the excel-file. I have an Application-object and a Workbook-object. I call...
4
by: Jonny | last post by:
Hello Group How do I open a Save File Dialog from an ASPX page behind a browse button? Any help would be fantastic!! I am using ASP.NET 1.1 using VB.NET as the coding language TIA
2
by: JimLad | last post by:
Hi, First of all I didn't design this website, but I have been asked to fix it with the minimum fuss! Website is using .NET on IIS6 with an Excel Interop to produce reports. The website...
2
by: AccessHunter | last post by:
Hi, In my VBA code I am saving an excel spreadsheet with data from a table. I would like to prompt the Save File or Save As Dialog box with a default File Name, after opening the spreadsheet. ...
1
by: Rob Nicholson | last post by:
I've managed to write an ASP.NET v2 web page where the prompt to save the password doesn't appear :-( Not sure why it's not working. Autocomplete on the text boxes is working but when you enter...
5
by: =?Utf-8?B?Qi4gQ2hlcm5pY2s=?= | last post by:
I've been tasked to translate a C# program to VB. (Dot Net 2.0.) I'm starting from scratch with no documentation and I'm trying to understand what the original programmer did. (The 'original...
0
by: Swys | last post by:
Hi there, I am currently trying to write myself a wrapper class for the Excel interop services. I had a problem on closing the process, but just decided to kill it in the end. My current problem,...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.