在一个项目中,需要从Excel文件导入数据然后再datagridview上显示,同时也需要右键datagridview时可以将数据另存为excel文件,于是写了这两个工具方法。本文提供了两个方法用于Excel和DataTable之间相互转化。
1, 从Excel文件、CSV文件导入到DataTable:
- public static DataTable csvToDataTable(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到出到CSV文件:
- 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();
- }
- }
本文出自 “小何贝贝的技术空间” 博客,请务必保留此出处http://babyhe.blog.51cto.com/1104064/407065