码迷,mamicode.com
首页 > 其他好文 > 详细

Excel操作--使用NPOI导入导出Excel为DataTable

时间:2016-02-17 14:28:02      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

1.ExcelHelper封装

技术分享
 1 namespace NPOI操作Excel
 2 {
 3     public class ExcelHelper
 4     {
 5         /// <summary>
 6         /// DataTable转成Excel,返回一个文件流
 7         /// </summary>
 8         /// <param name="dataTable"></param>
 9         /// <returns></returns>
10         public static Stream DatatableToExcel(DataTable dataTable)
11         {
12             IWorkbook wk = new HSSFWorkbook();
13             MemoryStream ms = new MemoryStream();
14             ISheet sheet = wk.CreateSheet();
15             IRow headerRow = sheet.CreateRow(0);
16 
17             //处理标题部分
18             foreach (DataColumn column in dataTable.Columns)
19             {
20                 headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
21             }
22             //处理table中的数据
23             int rowIndex = 1;
24             foreach (DataRow row in dataTable.Rows)
25             {
26                 IRow dataRow = sheet.CreateRow(rowIndex);
27                 foreach (DataColumn column in dataTable.Columns)
28                 {
29                     //column.Ordinal得到从0开始的列的位置,column.ColumnName的到列的名称
30                     dataRow.CreateCell(column.Ordinal).SetCellValue(row[column.ColumnName].ToString());
31                 }
32                 rowIndex++;
33             }
34             wk.Write(ms);
35             ms.Flush();
36             ms.Position = 0;
37 
38             sheet = null;
39             headerRow = null;
40             return ms;
41         }
42 
43         /// <summary>
44         /// 读取Excel文件,转换成DataTable
45         /// </summary>
46         /// <param name="ExcelFileStream">读取到Excel的文件流</param>
47         /// <param name="SheetIndex">表的索引</param>
48         /// <param name="HeaderRowIndex">标题行的索引</param>
49         /// <returns></returns>
50         public static DataTable DataTableFromExcel(Stream ExcelFileStream, int SheetIndex, int HeaderRowIndex)
51         {
52             IWorkbook wk = new HSSFWorkbook(ExcelFileStream);
53             ISheet sheet = wk.GetSheetAt(SheetIndex);
54 
55             DataTable table = new DataTable();
56 
57             IRow headerRow = sheet.GetRow(HeaderRowIndex);
58             int cellCount = headerRow.LastCellNum;
59 
60             //处理标题行的数据
61             for (int i = headerRow.FirstCellNum; i < cellCount; i++)
62             {
63                 DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
64                 table.Columns.Add(column);
65             }
66             //循环遍历sheet中的每一行,读取每一单元格的数据,同时创建table中的每一行,填充数据
67             int rowCount = sheet.LastRowNum;
68             for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
69             {
70                 IRow row = sheet.GetRow(i);
71                 //以表的格式创建一个新的行
72                 DataRow dataRow = table.NewRow();
73 
74                 for (int j = row.FirstCellNum; j < cellCount; j++)
75                 {
76                     if (row.GetCell(j) != null)
77                     {
78                         dataRow[j] = row.GetCell(j).ToString();
79                     }
80                 }
81                 //dataRow的数据填充好后把行加到表中
82                 table.Rows.Add(dataRow);
83             }
84             ExcelFileStream.Close();
85             wk = null;
86             sheet = null;
87             return table;
88         }
89     }
90 }
View Code

2.SqlHelper封装

技术分享
 1 namespace NPOI操作Excel
 2 {
 3     public static class SqlHelper
 4     {
 5         //从配置文件中读取连接字符串
 6         private static readonly string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
 7         //执行命令的方法 insert update delete
 8         public static int ExecuteNonquey(string sql, params SqlParameter[] ps)
 9         {
10             using (SqlConnection con = new SqlConnection(conStr))
11             {
12                 using (SqlCommand cmd = new SqlCommand(sql, con))
13                 {
14                     con.Open();
15                     cmd.Parameters.AddRange(ps);
16                     return cmd.ExecuteNonQuery();
17                 }
18             }
19         }
20         //获取首行首列
21         public static object ExecuteScalar(string sql, params SqlParameter[] ps)
22         {
23             using (SqlConnection con = new SqlConnection(conStr))
24             {
25                 using (SqlCommand cmd = new SqlCommand(sql, con))
26                 {
27                     con.Open();
28                     cmd.Parameters.AddRange(ps);
29                     return cmd.ExecuteScalar();
30                 }
31             }
32         }
33 
34         //获取读取数据库的对象
35         public static SqlDataReader ExecuteDataReader(string sql, params SqlParameter[] ps)
36         {
37             SqlConnection con = new SqlConnection(conStr);
38             using (SqlCommand cmd = new SqlCommand(sql, con))
39             {
40                 try
41                 {
42                     con.Open();
43                     cmd.Parameters.AddRange(ps);
44                     return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
45                 }
46                 catch (Exception ex)
47                 {
48                     con.Close();
49                     con.Dispose();
50                     throw ex;
51                 }
52             }
53         }
54         //获取结果集
55         public static DataTable GetDataTable(string sql, params SqlParameter[] ps)
56         {
57             //构造数据表,用于接收查询结果
58             DataTable dt = new DataTable();
59             //构造适配器对象
60             using (SqlDataAdapter sda = new SqlDataAdapter(sql, conStr))
61             {
62                 //添加参数
63                 sda.SelectCommand.Parameters.AddRange(ps);
64                 //执行
65                 sda.Fill(dt);
66                 return dt;
67             }
68         }
69 
70     }
71 }
View Code

3.winform中操作

3.1从数据库读取数据导入到Excel中

技术分享
 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             DataTable dt = SqlHelper.GetDataTable("select * from t_persons");
 4             MemoryStream ms = ExcelHelper.DatatableToExcel(dt) as MemoryStream;
 5 
 6             string saveFileNme = "";
 7             bool fileSaved = false;
 8             //保存文件对话框
 9             SaveFileDialog saveDialog = new SaveFileDialog();
10             //设置默认的文件类型
11             saveDialog.DefaultExt = "xls";
12             saveDialog.Filter = "Excel文件|*.xls";
13             //设置文件名
14             saveDialog.FileName = "保存";
15             saveDialog.ShowDialog();
16             //获得文件全路径
17             saveFileNme = saveDialog.FileName;
18             if (saveFileNme.IndexOf(":") < 0) return;
19             if (saveFileNme != "")
20             {
21                 try
22                 {
23                     FileStream fs = new FileStream(saveDialog.FileName, FileMode.Create);
24                     fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
25                     ms.Close();
26                     ms.Dispose();
27                     fs.Close();
28                     fileSaved = true;
29                 }
30                 catch (Exception ex)
31                 {
32                     fileSaved = false;
33                     MessageBox.Show("导出文件出错,文件可能正在被占用\n" + ex.Message);
34                 }
35             }
36             else
37             {
38                 fileSaved = false;
39             }
40             GC.Collect();//强行销毁
41             if (fileSaved&&File.Exists(saveFileNme))
42             {
43                 MessageBox.Show("导出成功", "通知");
44             }
45             else
46             {
47                 MessageBox.Show("导出失败", "通知");
48             }
49         }
View Code

技术分享

3.2读取Excel文件,转换成DataTable绑定到DataGridView上

技术分享
 1         private void button2_Click(object sender, EventArgs e)
 2         {
 3             //打开文件对话框
 4             OpenFileDialog fileDialog=new OpenFileDialog();
 5             //指定要打开文件的格式
 6             fileDialog.Filter = "Excel文件|*.xls";
 7             //设置默认打开路径
 8             fileDialog.InitialDirectory = @"C:\Users\LWP1398\Desktop";
 9             if (fileDialog.ShowDialog()==DialogResult.OK)
10             {
11                 string fileName = fileDialog.FileName;//得到文件全路径
12                 using (FileStream fsRead=new FileStream(fileName,FileMode.Open,FileAccess.Read))
13                 {
14                     DataTable dt = ExcelHelper.DataTableFromExcel(fsRead, 0, 0);
15                     dgv.DataSource = dt;
16                 }
17             }
18             MessageBox.Show("ok");
19         }
20     }
View Code

技术分享

 NPOI目前主要还是操作xls文件,对操作xlsx文件支持得不是很好

Excel操作--使用NPOI导入导出Excel为DataTable

标签:

原文地址:http://www.cnblogs.com/CSharpLover/p/5194997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!