标签:style blog http color os io ar for 数据
最近有个项目需要用到excel导入,要求是excel有哪些字段不固定,对应到数据库的字段需要动态配置,而且客户可以随意修改,在网上也找了一些方法,也做过一些测试,最终选择NPOI,于此相关的帖子网上也有很多,在此,我只是记录下研究的成果,如果代码有什么问题,还请大家不吝赐教。。。。以下只是读取excel部分。。。
1 public class DataTableRenderToExcel
2 {
3 public DataTableRenderToExcel()
4 {
5 //
6 // TODO: 在此加入建構函式的程式碼
7 //
8 }
9 static private IWorkbook workbook = null;
10 static private ISheet sheet = null;
11 static private DataTable dt_data = null;
12
13 static private string _filepath;
14 static public string FilePath
15 {
16 set { _filepath = value; }
17 get { return _filepath; }
18 }
19 static private string _sheetname;
20 static public string SheetName
21 {
22 set { _sheetname = value; }
23 get { return _sheetname; }
24 }
25
26
27 #region NPOI导入EXCEL
28 /// <summary>
29 /// 创建工作簿
30 /// </summary>
31 private static IWorkbook CreateWorkBook()
32 {
33 try
34 {
35 using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
36 {
37 if (FilePath.IndexOf(".xlsx") > 0) // 2007或2010版本
38 return new XSSFWorkbook(fs);
39 else
40 return new HSSFWorkbook(fs); // 2003版本
41 }
42 }
43 catch (Exception ex)
44 {
45 throw ex;
46 }
47 }
48 /// <summary>
49 /// 获取EXCEL工作表sheet集合
50 /// </summary>
51 /// <param name="fileName"></param>
52 /// <returns></returns>
53 public static List<string> ExcelSheetToDT()
54 {
55 List<string> sheetName = new List<string>();
56 try
57 {
58 if (workbook == null)
59 workbook = CreateWorkBook();
60
61 int sheetCount = workbook.NumberOfSheets;
62
63 for (int i = 0; i < sheetCount; i++)
64 {
65 sheetName.Add(workbook.GetSheetName(i));
66 }
67 }
68 catch (Exception ex)
69 {
70 throw ex;
71 }
72 return sheetName;
73 }
74 /// <summary>
75 /// 返回EXCEL工作簿sheet
76 /// </summary>
77 /// <param name="sheetName"></param>
78 /// <returns></returns>
79 private static ISheet GetExcelSheet()
80 {
81 try
82 {
83 if (workbook == null)
84 workbook = CreateWorkBook();
85
86 if (SheetName == string