473,404 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

How to Retrieve data from c#.net to excel and store file at user desired location?

hello,
I am try to retrieve data from my c# windows application to excel sheet and store this .xls file to desired location. but my problem is that my code save excel file at a predefined location.
Expand|Select|Wrap|Line Numbers
  1. private Excel.Application m_objExcel = null;
  2.         private Excel.Workbooks m_objBooks = null;
  3.         private Excel._Workbook m_objBook = null;
  4.         private Excel.Sheets m_objSheets = null;
  5.         private Excel._Worksheet m_objSheet = null;
  6.         private Excel.Range m_objRange = null;
  7.         private Excel.Font m_objFont = null;
  8.         private Excel.QueryTables m_objQryTables = null;
  9.         private Excel._QueryTable m_objQryTable = null;
  10.         // Frequenty-used variable for optional arguments.
  11.         private object m_objOpt = System.Reflection.Missing.Value;
  12.  
  13.         // Paths used by the sample code for accessing and storing data.
  14.         private object m_strSampleFolder = Application.StartupPath  + "\\ExcelData\\" ;
  15.  
  16.         private void xlsheet()
  17.         {
  18.             // Start a new workbook in Excel.
  19.  
  20.             m_objExcel = new Excel.Application();
  21.             m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
  22.             m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));
  23.             m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
  24.             m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
  25.             // Create an array for the headers and add it to cells A1:C1.
  26.             object[] objHeaders = { "X-Axis CH1", "Y-Axis CH1","Nilesh", "X-Axis CH2", "Y-Axis CH2" };
  27.             m_objRange = m_objSheet.get_Range("A1", "E1");
  28.             m_objRange.set_Value(m_objOpt, objHeaders);
  29.             m_objFont = m_objRange.Font;
  30.             m_objFont.Bold = true;
  31.             // Create an array with 3 columns and 100 rows and add it to
  32.             // the worksheet starting at cell A2.
  33.             object[,] objData = new Object[bufn.Length, 5];
  34.             Int64 c_xl1 = 0, c_xl2=0;
  35.             for (int r = 0; r < bufn.Length; r++)
  36.             {
  37.                 objData[r, 0] = c_xl1.ToString();
  38.                 objData[r, 1] = (bufn[r] + vsc2).ToString();
  39.                 c_xl1 += 1;
  40.                 objData[r, 3] = c_xl2.ToString();
  41.                 objData[r, 4] = (bufb[r] + vsc4).ToString();
  42.                 c_xl2 += 1;
  43.             }
  44.             m_objRange = m_objSheet.get_Range("A2", m_objOpt);
  45.             m_objRange = m_objRange.get_Resize(bufn.Length, 5);
  46.             m_objRange.set_Value(m_objOpt, objData);
  47.             // Save the workbook and quit Excel.
  48.            m_objBook.SaveAs(m_strSampleFolder+nm.ToString()+"Book24.xlsx", m_objOpt, m_objOpt,
  49.                 m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
  50.                 m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
  51.             m_objBook.Close(false, m_objOpt, m_objOpt);
  52.             m_objExcel.Quit();
  53.             nm += 1;
  54.         }
  55.  
  56.  
  57.  
  58. private void iFormGlassButton3_Click(object sender, EventArgs e)
  59.         {
  60.             xlsheet();
  61.         }
  62.  
This code saves file at predefine location


Expand|Select|Wrap|Line Numbers
  1. private object m_strSampleFolder = Application.StartupPath  + "\\ExcelData\\;
Now i am trying to us SaveFileDialog control which save file to desired location like this


Expand|Select|Wrap|Line Numbers
  1. SaveFileDialog saveFileDialog1 = new SaveFileDialog();
  2.             saveFileDialog1.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
  3.             saveFileDialog1.Title = "Save an excel File";
  4.             saveFileDialog1.DefaultExt = "xls";
  5.             saveFileDialog1.ShowDialog();
  6.  
  7.             // If the file name is not an empty string open it for saving.
  8.             if (saveFileDialog1.FileName != "")
  9.             {
  10.                 // Saves the Image via a FileStream created by the OpenFile method.
  11.                 System.IO.FileStream fs =
  12.                    (System.IO.FileStream)saveFileDialog1.OpenFile();
  13.                 // Saves the Image in the appropriate ImageFormat based upon the
  14.                 // File type selected in the dialog box.
  15.                 // NOTE that the FilterIndex property is one-based.
  16.  
  17.  
  18.                 fs.Close();
  19. }
both of functions work properly but my Requirement is that i want to store excel sheet at desired location.
please help me

Thanks and Regards
Nilesh
Mar 3 '11 #1
1 5630
Aimee Bailey
197 Expert 100+
Have you considered CSV export instead? it's much easier, excel still open's the file's, and it would avoid using an interop with office to use it.

I try to discourage interops as you don't always know if the target computer your application will run on will use Microsoft Office (which is a requirement for this to work).

Infact here's an example using the DataTable...

Expand|Select|Wrap|Line Numbers
  1. public void SaveCSV(DataTable data, string filename)
  2. {
  3.     List<string> csv_lines = new List<string>();
  4.  
  5.     string csv_header = "";
  6.     foreach (DataColumn col in data.Columns)
  7.     {
  8.         csv_header += col.ColumnName + ", ";
  9.     }
  10.     csv_lines.Add(csv_header.TrimEnd(' ', ','));
  11.  
  12.     foreach (DataRow row in data.Rows)
  13.     {
  14.         string csv_line = "";
  15.         foreach (DataColumn col in data.Columns)
  16.         {
  17.             string val = row[col].ToString();
  18.             double dval = 0;
  19.  
  20.             if (double.TryParse(val, out dval))
  21.             {
  22.                 csv_line += string.Format("{0}, ", dval);
  23.             }
  24.             else
  25.             {
  26.                 csv_line += string.Format("'{0}', ", val);
  27.             }
  28.  
  29.         }
  30.         csv_lines.Add(csv_line.TrimEnd(' ',','));
  31.     }
  32.     File.WriteAllLines(filename, csv_lines);
  33. }
  34.  
Mar 4 '11 #2

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

Similar topics

14
by: pmud | last post by:
Hi, I need to use an Excel Sheet in ASP.NET application so that the users can enter (copy, paste ) large number of rows in this Excel Sheet. Also, Whatever the USER ENETRS needs to go to the...
17
by: Philip Wagenaar | last post by:
I have an excel sheet that has several lines. Each line is an order. Example: 1 Paper 10 2 Pencils 20 etc... When the excel sheet is filled out I want the user to press a...
1
by: friendlyrohit | last post by:
Hi All !!! Can anybody help me out, how to retrieve a desired column's data from an existing excel sheet through the vb code....... Dim strData As String Dim ts As TextStream ...
8
by: hyper-sensitive | last post by:
Hi Can some body suggest me which approach I should follow to import millions of records from data base into an excel sheet? I am working with ver. 2000 of MS-Excel . The requirement is to...
2
by: thangsan | last post by:
Hi Friends, In my project i need to Export the Data from Sql server to Excel Sheet. It should be auto schedulder certain intervals(months). i want to store the Excel sheet in .CSV ...
1
by: jayafeb83 | last post by:
First I created One excel sheet, 3 rows and 3 columns and I retrieve excel data using ASP, that one I got the Answer I have to know thatretrieve from excel sheet and store the excel data in...
1
by: pvenu | last post by:
Hi, I know basic perl (regular expressions, pattern matching, string manipulation, reading writing into text files). Yet, my requirement is to read an input text file -> process this input file...
7
by: TG | last post by:
hi! I am trying to create a sql server table from an excel sheet. Here is the code I have: 'This procedure the xlsx file and dumps it to a table in SQL Server
1
by: vtangella | last post by:
Hi Guys! Here i am using Apache POI for reading the Excel sheet in java and then i am capturing the excel sheet data into a ArrayList and then i am storing it in DB. Any Other way to store...
1
by: PeacefulSoul | last post by:
Hello, I have a lot of excel sheets which columns are slightly different, i want to import all of these sheets (one at a time) into ONE SQL TABLE. I'll give an example : Say ive written the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.