Solved

How to save data from database to Excel worksheet

Posted on 2009-04-05
32
1,188 Views
Last Modified: 2012-06-21
Hello all,

I'm new to C#.

I've made a simple database with a NAME grid and LASTNAME grid.

I want to save the data that I write in but when I press the SAVE button the data doesn't shown at my next run.

What is the best and easiest way to save my data?

And I want to save it to an Excel worksheet.
0
Comment
Question by:liorb
  • 16
  • 15
32 Comments
 
LVL 6

Expert Comment

by:Ramone_Hamilton
Comment Utility
I'm a little confused as to what is saving data where?  Do you have an application that you've created that's saving this data to the database/excel?  If so could you post a sample of the cpde that you added on your onClick event for your save button.
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
Ramon Hello

I've made a simple database with one Table that has two columns 'First Name' & 'Last Name'

I didn't wrote any code about saving the data from the table to an Excel worksheet, because I don't know how to do that.
Can you or anyone help me with that???
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
do u know to extract data from sql table .. ? or u want code for retrieving data from SQl and saving in excel
0
 
LVL 29

Assisted Solution

by:Gautham Janardhan
Gautham Janardhan earned 50 total points
Comment Utility
the following code will dump the data in a datatable to an excel file
Excel.Application ea = new Excel.ApplicationClass();
 

Excel.Workbook wb = ea.Workbooks.Open(template, 0, true, 5, "", "", true, 

Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
 

string currentSheet = "Daily Data";
 

Excel.Sheets eSheets = wb.Worksheets;

Excel.Worksheet eWs = (Excel.Worksheet)eSheets.get_Item(currentSheet);

                  

ea.Visible = true;

                  

DataTable table = ds.Tables[0]; 

                  

int ColumnIndex=0; 

foreach(DataColumn col in table.Columns) 

{ 

      ColumnIndex++; 

      eWs.Cells[1,ColumnIndex]=col.ColumnName;

} 
 

int count = table.Rows.Count;
 

int rowIndex=0; 

foreach(DataRow row in table.Rows) 

{ 

      rowIndex++; 
 

      Console.WriteLine(count + " out of " + rowIndex);

      ColumnIndex=0; 

      foreach(DataColumn col in table.Columns) 

      { 

            ColumnIndex++;

            eWs.Cells[rowIndex+1,ColumnIndex] = row[col.ColumnName];

      } 

} 
 

Excel.Worksheet worksheet = (Excel.Worksheet)ea.ActiveSheet; 

worksheet.Activate(); 

}

Open in new window

0
 
LVL 1

Author Comment

by:liorb
Comment Utility
Thanks for the code

But the EXCEL word is not recognized!

What should I do to fix the problem?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
u have to add the excel library from the com tab..
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
th name will be Micorosoft.Excel.5.0 Object Library, the version will change according to the office vesion installed in ur machine
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
com tab????
adding Excel library - How do I do that???

Sorry but I'm very new to C#

Thanks
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
Figured it out - the way to add the Excel library!

In line 3

Excel.Workbook wb = ea.Workbooks.Open(template, .......

The word "template" is not recognized in my code, what this string represent?
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
'template' will be the path of the excel u want to open.
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
OK

You forgot to place " before and after the 'template' word
But still I keep getting this error:

Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))

How can I solve it???
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
when are u getting this error ?
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
I get the error at the OBJECT ORIGIN point

Here is the code line:

Excel.Workbook wb = ea.Workbooks.Open("myStringFile", 3, false , 1,"" ,"" , false , Excel.XlPlatform.xlWindows , "", false , false ,"" , true , true ,"" );
I've done some searching on the internet and found that if I change my regional settings to English(united states) the error will be solved - and it did!
But now the error changed on the same OBJECT ORIGIN point.
This is the new error:
The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility

Excel.Workbook wb = ea.Workbooks.Open("", 3, false , 1,"" ,"" , false , Excel.XlPlatform.xlWindows , "", false , false ,"" , true , true ,"" );

Open in new window

0
 
LVL 1

Author Comment

by:liorb
Comment Utility
No
Don't work!
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
are u getting the same exception ?...
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 1

Author Comment

by:liorb
Comment Utility
I wrote this code

I've started with populating the HEADERS first
I got an error on this line :
foreach (DataColumn col in table .Columns )
the error points to the table.columns and is as follows :
Object reference not set to an instance of an object.
How to solve that?
I'm sure that somthing missing but don't know what.


Microsoft.Office.Interop.Excel.Workbook book;

Microsoft.Office.Interop.Excel.Worksheet sheet;

Microsoft.Office.Interop.Excel.Application application;
 

application = new Microsoft.Office.Interop.Excel.ApplicationClass();

            

book = application.Workbooks.Add("");
 

sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets[1];

sheet.Name = "myStringFile";
 

Excel.Application ea = new Excel.ApplicationClass();
 

Excel.Workbook wb = ea.Workbooks.Open("myStringFile", 0, true, 5,

                Type.Missing, Type.Missing, true,

            Excel.XlPlatform.xlWindows, Type.Missing,

            true, false, 0, true, false, false);

                      

DataSet ds = new DataSet("testingdataDataSet");

DataTable table = ds.Tables["switch_detailsTableAdapter" ];
 

int ColumnIndex = 0;

foreach (DataColumn col in table .Columns )

{

   ColumnIndex++;

   sheet.Cells[1, ColumnIndex] = col.ColumnName;                

}
 

book.SaveAs("D:\\Visual Projects\\testingData\\myStringFile",

                Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12 ,

                Type .Missing , Type .Missing , false,

                false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,

                Type .Missing , Type .Missing , Type .Missing ,

                Type .Missing , Type .Missing );
 

book.Close(true, Type .Missing , Type .Missing );

application.Visible = true; //true=open Excel ; false=don't open Excel
 

application.Quit();

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
change
DataTable table = ds.Tables["switch_detailsTableAdapter" ];
to
DataTable table = ds.Tables[0 ]; and try
 
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
Still an error :

"Cannot find table 0."
 
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
u are just initializing it and there wont be any data int it ? what are u trying to write to the excel and where does the data come from ?
DataSet ds = new DataSet("testingdataDataSet");
DataTable table = ds.Tables["switch_detailsTableAdapter" ];
 
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
Very simple
As I wrote before - I have made a simple data base in C#
The DATASET is called "testingdataDataSet"
In it I have made a simple TABLE with 4 parameters(columns): "switchID, switchName, switchLast, switchLocation"

What the program supose to do is to get the data that I write into those parameters and save/load them into/from an excel sheet.
And thats all !

I have two problems in which you helped me greatly!

The first one is when I press the save button the program don't keep the data I write into it when I rerun the program.
also I cann't see the data I write during running mode in editing mode when pressing "preview data"

The second one is saving and loading data to and from an Excel sheet (on that problem we focused on)
I hope that now it's more clear
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
is the testingdataDataSet created using the designer in VS ? the u can instantiate it using the proxy class testingdataDataSet data = new testingdataDataSet(); then u can use the data.Load() function to load the data using the connection u specified in the desginer.then u can use that data set instead of DataSet ds = new DataSet("testingdataDataSet");
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
So the code should be somthing like this???

testingdataDataSet data = new testingdataDataSet();
data.load();  //don't know what to write in the brackets
DataSet ds = new DataSet("data");
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
testingDataSet is the data set where u will have the data and u dont need to initialize a new data set ( DataSet ds = new DataSet("data");)
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
OK

What should be in the brackets of the data.load(???)
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
if testdataset is generated using the VS designer it will have a load function without any parameters which loads the data into the dataset from the data source u specified
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
OK
Did it the columns headers are saved in the Excel worksheet

And for the last part - populating the rows
I've copied your code and nothing happens!
The rows in the Excel sheet don't fill up.

Here is the code:


private void button2_Click(object sender, EventArgs e)

        {

            Microsoft.Office.Interop.Excel.Workbook book;

            Microsoft.Office.Interop.Excel.Worksheet sheet;

            Microsoft.Office.Interop.Excel.Application myApplication;
 

            myApplication = new Microsoft.Office.Interop.Excel.ApplicationClass();

            

            book = myApplication.Workbooks.Add(Type .Missing );
 

            sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets[1];

            sheet.Name = "myStringFile";
 

            Excel.Application ea = new Excel.ApplicationClass();
 

            testingdataDataSet data = new testingdataDataSet();

           

            DataTable myTable = data.Tables[0];

                            
 

            int ColumnIndex = 0;

            
 

                foreach (DataColumn myColumn in myTable.Columns)

                {

                    ColumnIndex++;

                    sheet.Cells[1, ColumnIndex] = myColumn.ColumnName;

                    sheet.Columns.AutoFit();

                }
 

                int count = myTable.Rows.Count;
 

                int rowIndex = 0;

                foreach (DataRow row in myTable.Rows)

                {

                    rowIndex++;
 

                    Console.WriteLine(count + " out of " + rowIndex);

                    ColumnIndex = 0;

                    foreach (DataColumn col in myTable.Columns)

                    {

                        ColumnIndex++;

                        sheet.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];

                    }

                } 
 

            
 

            book.SaveAs("D:\\Visual Projects\\testingData\\myStringFile",

                Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12 ,

                Type .Missing , Type .Missing , false,

                false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,

                false , Type .Missing , Type .Missing ,

                Type .Missing , true  );
 

            book.Close(true, "myStringFile",true );

            myApplication.Visible = true; //true=open Excel ; false=don't open Excel

                        

            myApplication.Workbooks.Close();

            myApplication.Quit();

        }

Open in new window

0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
testingdataDataSet data = new testingdataDataSet();
data.Load();          
DataTable myTable = data.Tables[0];
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
The "data.load();" is marked with a red line
Somthing must be written in the brackets !

Will the - "data.load" - fill the cells in the Excel file???
0
 
LVL 29

Expert Comment

by:Gautham Janardhan
Comment Utility
no data.Load loads data into the dataset and from the dataset u populate into the excel using the rest of the code .. U need to check the TestingDataSet class or use intellisense to see what is the overload for the Load method.
0
 
LVL 1

Author Comment

by:liorb
Comment Utility
With the intelisense the data.load() needs:

IDataReader reader , loadoption loadoption , params string[] tables

I don't know what to place in each one of them
What should I do now???

0
 
LVL 1

Accepted Solution

by:
liorb earned 0 total points
Comment Utility
OK
Made some more advancment
But I solve one problem and a new one pops up

I know what to write inside the data.load() brackets and for the I need to write some more code
For the reader I need to write this line:

DataTableReader myReader = GetReader();

But the getreader() is marked red - the error says "does not exist in the current context"
How do I solve that????

Here is the code:


private void button2_Click(object sender, EventArgs e)

        {

            Microsoft.Office.Interop.Excel.Workbook book;

            Microsoft.Office.Interop.Excel.Worksheet sheet;

            Microsoft.Office.Interop.Excel.Application myApplication;
 

            myApplication = new Microsoft.Office.Interop.Excel.ApplicationClass(); //Start the EXCEL application

            

            book = myApplication.Workbooks.Add(""); //Adds a new Workbook
 

            sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets[1];

            sheet.Name = "myStringFile"; //Sets the name of the EXCEL file.

            DataTable testingData = new DataTable();

            DataTableReader myReader = GetReader(); 

            testingdataDataSet data = new testingdataDataSet();

            data.Load(myReader ,LoadOption.OverwriteChanges , testingData );

            DataTable myTable = data.Tables[0];

                  

            //Fill the columns headers

            int ColumnIndex = 0;

            

                foreach (DataColumn myColumn in myTable.Columns)

                {

                    ColumnIndex++;

                    sheet.Cells[1, ColumnIndex] = myColumn.ColumnName;

                    sheet.Columns.AutoFit();                    

                }
 

            //Fill the rows

            int count = myTable.Rows.Count;

            int rowIndex = 0;
 

            foreach (DataRow row in myTable.Rows)

            {

                rowIndex++;
 

                Console.WriteLine(count + " out of " + rowIndex);

                ColumnIndex = 0;
 

                foreach (DataColumn col in myTable.Columns)

                {

                    

                    ColumnIndex++;

                    sheet.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];

                }
 

            } 
 

            book.SaveAs("D:\\Visual Projects\\testingData\\myStringFile",

                Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12 ,

                Type .Missing , Type .Missing , false,

                false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,

                false , Type .Missing , Type .Missing ,

                Type .Missing , true  );
 

            book.Close(true, "myStringFile",true );

            myApplication.Visible = true; //true=open Excel ; false=don't open Excel

            myApplication.Workbooks.Close();

            myApplication.Quit();

                                                

        }

Open in new window

0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now