走进一步,发掘一处。勇于,敢于。
jtans

导航

统计
  • 随笔 - 9
  • 文章 - 5
  • 评论 - 20
  • 引用 - 0
公告
 
  1 public static class ExcelUtil
  2 {
  3     // Methods
  4     public static DataTable GetDataTable(Stream stream)
  5     {
  6         HSSFWorkbook workbook;
  7         try
  8         {
  9             workbook = new HSSFWorkbook(stream);
 10         }
 11         catch (Exception exception)
 12         {
 13             throw exception;
 14         }
 15         ISheet sheetAt = workbook.GetSheetAt(0);
 16         IEnumerator rowEnumerator = sheetAt.GetRowEnumerator();
 17         DataTable table = new DataTable();
 18         IRow row = sheetAt.GetRow(0);
 19         if (row != null)
 20         {
 21             for (int j = 0; j < row.LastCellNum; j++)
 22             {
 23                 ICell cell = row.GetCell(j);
 24                 if (cell == null)
 25                 {
 26                     table.Columns.Add("cell" + j.ToString());
 27                 }
 28                 else
 29                 {
 30                     table.Columns.Add(cell.ToString());
 31                 }
 32             }
 33         }
 34         int count = table.Columns.Count;
 35         for (int i = 0; rowEnumerator.MoveNext(); i++)
 36         {
 37             if (i > 0)
 38             {
 39                 IRow current = (HSSFRow) rowEnumerator.Current;
 40                 DataRow row3 = table.NewRow();
 41                 for (int k = 0; k < count; k++)
 42                 {
 43                     ICell cell2 = current.GetCell(k);
 44                     if (cell2 == null)
 45                     {
 46                         row3[k] = null;
 47                     }
 48                     else
 49                     {
 50                         row3[k] = cell2.ToString();
 51                     }
 52                 }
 53                 table.Rows.Add(row3);
 54             }
 55         }
 56         return table;
 57     }
 58 
 59     public static DataTable GetDataTable(string filePath)
 60     {
 61         HSSFWorkbook workbook;
 62         try
 63         {
 64             using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
 65             {
 66                 workbook = new HSSFWorkbook(stream);
 67             }
 68         }
 69         catch (Exception exception)
 70         {
 71             throw exception;
 72         }
 73         ISheet sheetAt = workbook.GetSheetAt(0);
 74         IEnumerator rowEnumerator = sheetAt.GetRowEnumerator();
 75         DataTable table = new DataTable();
 76         IRow row = sheetAt.GetRow(0);
 77         if (row != null)
 78         {
 79             for (int j = 0; j < row.LastCellNum; j++)
 80             {
 81                 ICell cell = row.GetCell(j);
 82                 if (cell == null)
 83                 {
 84                     table.Columns.Add("cell" + j.ToString());
 85                 }
 86                 else
 87                 {
 88                     table.Columns.Add(cell.ToString());
 89                 }
 90             }
 91         }
 92         int count = table.Columns.Count;
 93         for (int i = 0; rowEnumerator.MoveNext(); i++)
 94         {
 95             if (i > 0)
 96             {
 97                 IRow current = (HSSFRow) rowEnumerator.Current;
 98                 DataRow row3 = table.NewRow();
 99                 for (int k = 0; k < count; k++)
100                 {
101                     ICell cell2 = current.GetCell(k);
102                     if (cell2 == null)
103                     {
104                         row3[k] = null;
105                     }
106                     else
107                     {
108                         row3[k] = cell2.ToString();
109                     }
110                 }
111                 table.Rows.Add(row3);
112             }
113         }
114         return table;
115     }
116 
117     /// <summary>
118       /// 导入数据到excel文件
119       /// </summary>
120       /// <param name="data">待导入的数据</param>
121       /// <param name="fileName">文件路径</param>
122       /// <param name="sheetName">excel表名</param>
123       /// <param name="hiddenColmnIndexs">隐藏列索引</param>
124       /// <param name="header">列头字典;原始列头=>重命名列名</param>
125       /// <param name="redHeaderClomnIndexs">标记红色加粗的列索引</param>
126       /// <param name="comments">列头批注字典;列名=>批注内容</param>
127       /// <returns></returns>
128         public static string SetDataTableToExcel(DataTable data,string fileName, string sheetName, int[] hiddenColmnIndexs = null, Dictionary<string, string> header = null,int[] redHeaderClomnIndexs = null,Dictionary<string,string> comments= null)
129         {
130             int num4 = 0;
131             int num = 0;
132             int column = 0;
133             int rownum = 0;
134             ISheet sheet = null;
135             IWorkbook workbook = new HSSFWorkbook();
136             //todo:tans
137            var stream = new FileStream(fileName ,FileMode.OpenOrCreate,FileAccess.ReadWrite);
138            
139             try
140             {
141                 sheet = workbook.CreateSheet(sheetName);
142               
143                 
144                 IRow row = sheet.CreateRow(0);
145                 column = 0;
146                 int maxCount = Math.Max(header!=null ? header.Count : 0 , data.Columns.Count);
147 
148                 IDrawing patr1 = sheet.CreateDrawingPatriarch();// as HSSFPatriarch;
149                 //创建列头
150                 while (column < data.Columns.Count)
151                 {
152                     var col = data.Columns[column];                   
153                     var colName = col.ColumnName;
154                     ICell cell = row.GetCell(column);
155                     if (header!=null && header.ContainsKey(colName))
156                     {
157                         string temp = header[colName];//列重命名
158                         header.Remove(colName);
159                         cell = row.CreateCell(column);
160                         cell.SetCellValue(temp);
161                     }
162                     //创建批注
163                     colName = cell.StringCellValue;
164                     if (comments!=null && comments.ContainsKey(colName))
165                     {
166                         var commentStr = comments[colName];
167                         IComment comment1 = patr1.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 3, 3, 7));// as HSSFComment;
168                         comment1.String = new HSSFRichTextString(commentStr);
169                         cell.CellComment = comment1;
170                     }
171                     column++;
172                 }
173                 //附加列头
174                 int colCount = data.Columns.Count;
175                 foreach (var colName in header.Keys)
176                 {
177                     row.CreateCell(colCount).SetCellValue(header[colName]);
178                     colCount++;
179                 }
180                 //设置列头样式
181                 redHeaderClomnIndexs = redHeaderClomnIndexs ?? new int[]{};
182                 for (int i = 0, l=0, rl= redHeaderClomnIndexs.Length; i < row.Cells.Count; i++,l++)
183                 {
184                     var cell = row.GetCell(i);
185                     if (cell==null)
186                     {
187                         continue;
188                     }
189                     //设置字体
190                     IFont font = workbook.CreateFont();
191                     font.Boldweight = (short)FontBoldWeight.BOLD;
192                     if (l < rl)
193                     {
194                         int index = redHeaderClomnIndexs[l];
195                         cell = row.GetCell(index);
196                         font.Color = (short)FontColor.RED;
197                     }
198                     //设置样式
199                     ICellStyle style = workbook.CreateCellStyle();
200                     style.Alignment = HorizontalAlignment.CENTER;
201                     style.SetFont(font);
202 
203                     cell.CellStyle = style;
204                 }
205                //创建数据列,并填充数据
206                 rownum = 1;
207                 for (num = 0; num < data.Rows.Count; num++)
208                 {
209                     IRow row2 = sheet.CreateRow(rownum);
210                     for (column = 0; column < data.Columns.Count; column++)
211                     {
212                         row2.CreateCell(column).SetCellValue(data.Rows[num][column].ToString());
213                     }
214                     rownum++;
215                 }
216                 //设置隐藏列
217                 if (hiddenColmnIndexs != null && hiddenColmnIndexs.Length <= column)
218                 {
219                     for (int i = 0, l = hiddenColmnIndexs.Length; i < l; i++)
220                     {
221                         sheet.SetColumnHidden(hiddenColmnIndexs[i], true);
222                     }
223                 }
224                 //当创建完毕所有cell,设置居中才有效
225                 for (int i = 0; i < row.Cells.Count; i++)
226                 {
227                      sheet.AutoSizeColumn(i);
228                 }
229                 workbook.Write(stream);
230             }
231             catch (Exception ex)
232             {
233                 return null;
234             }
235             finally
236             {
237                 stream.Close();
238             }
239            return fileName;
240         }
241 }
242 
243  

 

posted on 2015-02-06 10:38 jtans 阅读(...) 评论(...) 编辑 收藏