C # Create an Excel file and export the data to an Excel file

Source: Internet
Author: User
Tags ole

Tool Material:

Windows 7,visual Studio, Microsoft Office 2007

Create a solution

Menu new Project Windows Forms application:

Add Related components:

Add two DataGridView, a TextBox, two buttons, such as:

To add an Excel resource:

C # creates an Excel file, where you actually extract a pre-created Excel file from the resource, and after the file extraction succeeds, you use the OLE DB method to connect to Excel and write the data to the Excel file.

Create a new Excel file in the folder and set the column name in the first row of the Sheet1 table:

Double-click the "Resources.resx" file to open the resource File view:

Add an existing file, select the Excel file you just created

Extracting an Excel file from a resource [CSharp]View Plaincopy
  1. String Excelpath = AppDomain.CurrentDomain.BaseDirectory + "Excel" + DateTime.Now.Ticks + ". xlsx";
  2. if (System.IO.File.Exists (Excelpath))
  3. {
  4. TextBox1.Text + = ("File already exists!  ");
  5. return;
  6. }
  7. Try
  8. {
  9. //Extract the Excel file from the resource
  10. System.IO.FileStream fs = new System.IO.FileStream (Excelpath, FileMode.OpenOrCreate);
  11. Fs. SetLength (0);
  12. Fs. Write (Properties.Resources.Excel, 0, Properties.Resources.Excel.Length);
  13. Fs. Close ();
  14. Fs. Dispose ();
  15. TextBox1.Text = "Extract Excel file successfully!"  "+ " \ r \ n ";
  16. }
  17. catch (System.Exception ex)
  18. {
  19. Excelpath = string.  Empty;
  20. TextBox1.Text + = ("Extract Excel file failed:" + ex.)  Message);
  21. TextBox1.Text + = ("\ r \ n");
  22. Application.doevents ();
  23. return;
  24. }
Defining a connection string [CSharp]View Plaincopy
    1. //define OLE DB connection string   
    2.             string  Strconn =  "provider=microsoft.ace.oledb.12.0; persist security info=false; "  +  "data source="  +  @excelPath  + 
    3.              Oledbconnection conn = new oledbconnection ();   
    4.             conn. connectionstring = strconn;  

Note: The value of Imex in the connection string is 10, and if it is 1 or 2, an error " operation must use an updatable query " is reported when an INSERT INTO statement is executed.

Display information for all tables in an Excel file in DataGridView1 [CSharp]View Plaincopy
    1. DataTable Oledt = conn.  GetOleDbSchemaTable (OleDbSchemaGuid.Tables, null);
    2. Datagridview1.datasource = Oledt;
    3. Datagridview1.show ();
Insert a few data into the "Sheet1" table, you need to add a "$" symbol after the table name to access the Excel table, the INSERT statement can not specify the column name [CSharp]View Plaincopy
  1. OleDbCommand cmd = null;
  2. Try
  3. {
  4. ///To insert a few data into the "Sheet1" table, you need to add a "$" symbol after the table name to access the Excel table, the INSERT statement can not specify the column name
  5. cmd = new OleDbCommand ("Insert into [sheet1$] Values (' abc ', ' Bac ', ' 0 ', ' 123456 ', ' Test ', ' testing ', ' AA ')", conn); (a,b,c,d,e,f,g)
  6. Cmd. ExecuteNonQuery ();
  7. Cmd. ExecuteNonQuery ();
  8. Cmd. ExecuteNonQuery ();
  9. Cmd. ExecuteNonQuery ();
  10. Cmd. ExecuteNonQuery ();
  11. }
  12. catch (System.Exception ex)
  13. {
  14. TextBox1.Text + = ("Insert data failed:" + ex.)  Message);
  15. TextBox1.Text + = ("\ r \ n");
  16. }
Display the contents of the table "Sheet1" in dataGridView2, you need to add the "$" symbol after the table name when accessing the Excel table [CSharp]View Plaincopy
    1. cmd = new OleDbCommand ("select * from [sheet1$]", conn);
    2. OleDbDataAdapter ADP = new OleDbDataAdapter (CMD);
    3. DataSet ds = new DataSet ();
    4. Adp. Fill (DS);
    5. Datagridview2.datasource = ds. Tables[0];
Traversing the contents of a schema [CSharp]View Plaincopy
  1. DataTable DT = conn. GetSchema ();
  2. for (int i = 0; i < dt. Columns.count; i++)
  3. {
  4. TextBox1.Text + = dt. Columns[i]. Caption;
  5. if (i + 1 < dt. Columns.count)
  6. {
  7. TextBox1.Text + = ",";
  8. }
  9. }
  10. for (int j = 0; j < dt. Rows.Count; J + +)
  11. {
  12. For (int i = 0; i < dt. Columns.count; i++)
  13. {
  14. if (dt. Rows[j][dt. Columns[i]]! = null)
  15. {
  16. TextBox1.Text + = dt. Rows[j][dt. Columns[i]]. ToString ();
  17. }
  18. Else
  19. {
  20. TextBox1.Text + = "null";
  21. }
  22. if (i + 1 < dt. Columns.count)
  23. {
  24. TextBox1.Text + = ",";
  25. }
  26. }
  27. TextBox1.Text + = ("\ r \ n");
  28. }
Close the Excel data connection [CSharp]View Plaincopy
  1. IF (Conn. State = connectionstate.closed)
  2. {
  3. Try
  4. {
  5. Conn. Close ();
  6. }
  7. catch (System.Exception ex)
  8. {
  9. TextBox1.Text + = ("Close Excel Data connection:" + ex.)  Message);
  10. TextBox1.Text + = ("\ r \ n");
  11. }
  12. }
Open File Directory [CSharp]View Plaincopy
      1. System.Diagnostics.Process.Start ("Explorer.exe", AppDomain.CurrentDomain.BaseDirectory);

C # Create an Excel file and export the data to an Excel file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.