In a project, you need to import data from an Excel file and display it on the datagridview. You also need to right-click the datagridview to save the data as an Excel file, so you have written these two tools. This article provides two methods for converting between EXCEL and able.
1. import data from an Excel or CSV file to a able:
- Public static datatable csvtoable able (string file)
- {
- String strconn = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + file + "; extended properties = 'excel 8.0; '"; // Excel File
- If (file. endswith (". CSV "))
- Strconn = "provider = Microsoft. jet. oledb.4.0; Data Source = "+ path +"; extended properties = 'text; HDR = yes; FMt = delimited; '"; // CSV file: HDR = yes -- first line is Header
- Oledbconnection oleconn = new oledbconnection (strconn );
- Oleconn. open ();
- Datatable sheets = oleconn. getoledbschematable (oledbschemaguid. Tables, null );
- If (sheets = NULL | sheets. Rows. Count <1)
- {
- Return NULL;
- }
- String filename = sheets. Rows [0] ["table_name"]. tostring (); // sheets. Rows [0] -- first sheet of Excel
- If (file. endswith (". CSV "))
- Filename = file. substring (file. lastindexof ("/"));
- String olestr = "select * from [" + filename + "]";
- If (file. endswith (". CSV "))
- Olestr = "select * from [" + filename + "]";
- Oledbcommand olecomm = new oledbcommand (olestr, oleconn );
- Olecomm. Connection = oleconn;
- Oledbdataadapter oleda = new oledbdataadapter ();
- Oleda. selectcommand = olecomm;
- Dataset DS = new dataset ();
- Oleda. Fill (DS );
- Oleconn. Close ();
- Return Ds. Tables [0];
- }
2. datatable to the CSV file:
- Public static void datatabletocsv (datatable table, string file)
- {
- String title = "";
-
- Filestream FS = new filestream (file, filemode. Create );
- Streamwriter Sw = new streamwriter (New bufferedstream (FS), system. Text. encoding. Default );
-
- For (INT I = 0; I <Table. Columns. Count; I ++)
- {
- Title + = table. Columns [I]. columnname + ",";
- }
- Title = title. substring (0, title. Length-1) + "\ n ";
- Sw. Write (title );
-
- Foreach (datarow row in table. Rows)
- {
- String line = "";
- For (INT I = 0; I <Table. Columns. Count; I ++)
- {
- Line + = row [I]. tostring () + ",";
- }
- Line = line. substring (0, line. Length-1) + "\ n ";
-
- Sw. Write (line );
- }
-
- Sw. Close ();
- FS. Close ();
- }
- }
-
-
This article is from the "little he Beibei's technical space" blog, please be sure to keep this http://babyhe.blog.51cto.com/1104064/407065