Excel文件读写操作(一)
生活随笔
收集整理的這篇文章主要介紹了
Excel文件读写操作(一)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
View Code 1 /// <summary>
2 /// 使用OLEDB對excel文件進行讀取,將Excel文件作為數據源
3 /// </summary>
4 /// <param name="p"></param>
5 /// <returns></returns>
6 private DataSet ExcelToDataSet(string fileName)
7 {
8 //定義連接字符串
9 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\";" + "data source=" + fileName;
10
11 //定義連接對象
12 OleDbConnection conn = new OleDbConnection(strConn);
13 try
14 {
15 //打開連接
16 conn.Open();
17 string strExcel = "";
18 //數據適配器
19 OleDbDataAdapter myCommand = null;
20 //數據集
21 DataSet ds = null;
22
23 //通過索引來獲取工作表的集合
24 System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
25 //獲取工作表名
26 string tableName = schemaTable.Rows[0][2].ToString().Trim();
27 //查詢語句
28 strExcel = "select * from [" + tableName + "]";
29 myCommand = new OleDbDataAdapter(strExcel, strConn);
30 ds = new DataSet();
31 //填充數據
32 myCommand.Fill(ds, "table1");
33 conn.Close();
34 return ds;
35 }
36 catch
37 {
38 MessageBox.Show("你選擇的文件不是標準的Excel文件");
39 return null;
40 }
41 } View Code 1 /// <summary>
2 /// 將datagridview的數據以文件流的形式寫入Excel文件
3 /// </summary>
4 /// <param name="dgv"></param>
5 public void DataGridViewToExcel(DataGridView dgv)
6 {
7 SaveFileDialog dlg = new SaveFileDialog();
8 dlg.Filter = "Execl files (*.xls)|*.xls";
9 dlg.CheckFileExists = false;
10 dlg.CheckPathExists = false;
11 dlg.FilterIndex = 0;
12 dlg.RestoreDirectory = true;
13 dlg.CreatePrompt = false;
14 dlg.Title = "保存為Excel文件";
15
16 if (dlg.ShowDialog() == DialogResult.OK)
17 {
18 Stream myStream;
19 myStream = dlg.OpenFile();
20 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
21 string columnTitle = "";
22 try
23 {
24 //寫入列標題
25 for (int i = 0; i < dgv.ColumnCount; i++)
26 {
27 if (i > 0)
28 {
29 columnTitle += "\t";
30 }
31 columnTitle += dgv.Columns[i].HeaderText;
32 }
33 sw.WriteLine(columnTitle);
34
35 //寫入列內容
36 for (int j = 0; j < dgv.Rows.Count; j++)
37 {
38 string columnValue = "";
39 for (int k = 0; k < dgv.Columns.Count; k++)
40 {
41 if (k > 0)
42 {
43 columnValue += "\t";
44 }
45 if (dgv.Rows[j].Cells[k].Value == null)
46 columnValue += "";
47 else
48 columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
49 }
50 sw.WriteLine(columnValue);
51 }
52 sw.Close();
53 myStream.Close();
54 MessageBox.Show("數據導出成功!", "提示", MessageBoxButtons.OK);
55 }
56 catch (Exception e)
57 {
58 MessageBox.Show(e.ToString());
59 }
60 finally
61 {
62 sw.Close();
63 myStream.Close();
64 }
65 }
66 }
轉載于:https://www.cnblogs.com/shuyajun/archive/2012/05/11/2496025.html
總結
以上是生活随笔為你收集整理的Excel文件读写操作(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 视频相关资源
- 下一篇: (转)字符型指针变量与字符数组的区别