我们会经常用到Excel,无论是存还是取,或是导出Excel,收集了一些常用到的Class,Function:
using System.Xml.Xsl;
using System.Xml;
using System.IO;
using System.Data.OleDb;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
public class UtilExcel { public static void SetPlainHeaders(HttpResponse response, HttpRequest request, string strFileName) { response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", strFileName)); response.ContentEncoding = Encoding.GetEncoding("big5"); } public static void SetHeaders(HttpResponse response, HttpRequest request, string strFileName) { response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", strFileName)); response.ContentEncoding = Encoding.GetEncoding("big5"); } public static void ExportPlain(string FileName, string strContent) { try { SetPlainHeaders(HttpContext.Current.Response, HttpContext.Current.Request, FileName); HttpContext.Current.Response.Write(strContent); HttpContext.Current.Response.End(); } catch (Exception ex) { throw ex; } } public static void ExportExcel(string FileName, string strContent) { try { SetHeaders(HttpContext.Current.Response, HttpContext.Current.Request, FileName); HttpContext.Current.Response.Write(strContent); HttpContext.Current.ApplicationInstance.CompleteRequest(); } catch (Exception ex) { throw ex; } } public static void ExportExcelWithHtml(DataTable dt, string FileName, List<ColumnInfo> lstHeaders) { ExportExcel(FileName, GenerateHtml(dt, lstHeaders)); } public static void ExportExcelWithHtml(DataTable dt, string FileName, List<ColumnInfo> lstHeaders, Dictionary<string, int> dicCaption, Dictionary<string, int> dicRowSpan, int leftPad) { ExportExcel(FileName, GenerateSpecialHtml(dt, lstHeaders, dicCaption, dicRowSpan, leftPad)); } public static void ExportExcelWithGroup(string strGroupField, DataTable dtData, List<ColumnInfo> lstHeaders, string strFileName, List<ColumnInfo> lstSumFields) { ExportExcel(strFileName, GenerateHtmlWithGroup(strGroupField, dtData, lstHeaders, lstSumFields)); } private static string GenerateSpecialHtml(DataTable dtData, List<ColumnInfo> lstHeaders, Dictionary<string, int> dicCaption, Dictionary<string, int> dicRowSpan, int leftPad) { Regex reg = new Regex("^0[0-9]+"); StringBuilder builder = new StringBuilder(); GenerateHtmlHeader(builder); builder.AppendFormat("<tr>"); for (int i = 0; i < leftPad; i++) { builder.AppendFormat("<td></td>"); } foreach (string strKey in dicCaption.Keys) { builder.AppendFormat("<td colspan='{0}'>[{1}]</td>", dicCaption[strKey] + 1, strKey); } builder.AppendFormat("</tr>"); GenerateCaption(builder, dtData, lstHeaders.Count); GenerateHeader(dtData, builder, lstHeaders, new List<ColumnInfo>()); int k = 0; foreach (DataRow drRow in dtData.Rows) { k++; builder.AppendFormat("<tr>"); foreach (ColumnInfo col in lstHeaders) { if (dtData.Columns.Contains(col.ColumnName) && col.IsShow) { if (col.ColumnType.ToLower().Equals(Public_ColumnType.BOOLEAN.ToString().ToLower())) { builder.AppendFormat("<td align='center' valign='middle'>{0}</td>", "1".Equals(drRow[col.ColumnName].ToString()) ? "是" : "否"); } else if (dicRowSpan.ContainsKey(drRow[col.ColumnName].ToString())) { if (k == 1) { builder.AppendFormat("<td rowspan='{0}' align='center' valign='middle'>{1}</td>", dicRowSpan[drRow[col.ColumnName].ToString()], drRow[col.ColumnName].ToString()); } if (k == dicRowSpan[drRow[col.ColumnName].ToString()]) { k = 0; } } else { builder.AppendFormat("<td align='center' valign='middle'>{0}</td>", drRow[col.ColumnName].ToString()); } } } builder.AppendFormat("</tr>"); } GenerateHtmlFooter(builder); return builder.ToString(); } private static string GenerateHtml(DataTable dtData, List<ColumnInfo> lstHeaders) { StringBuilder builder = new StringBuilder(); GenerateHtmlHeader(builder); GenerateCaption(builder, dtData, lstHeaders.Count); GenerateHeader(dtData, builder, lstHeaders, new List<ColumnInfo>()); GenerateContent(dtData, builder, lstHeaders); GenerateHtmlFooter(builder); return builder.ToString(); } private static string GenerateHtmlWithGroup(string strGroupField, DataTable dtData, List<ColumnInfo> lstHeaders, List<ColumnInfo> lstSumFields) { StringBuilder builder = new StringBuilder(); Regex reg = new Regex("^0[0-9]+"); GenerateHtmlHeader(builder); GenerateCaption(builder, dtData, lstHeaders.Count - 1); GenerateHeader(dtData, builder, lstHeaders, new List<ColumnInfo>() { new ColumnInfo() { ColumnName = strGroupField } }); foreach (ColumnInfo col in lstSumFields) { dtData.Columns.Add(new DataColumn() { ColumnName = string.Format("Total_{0}_{1}", strGroupField, col.ColumnName), DefaultValue = 0 }); dtData.Columns.Add(new DataColumn() { ColumnName = string.Format("Total_{0}", col.ColumnName), DefaultValue = 0 }); } string strNextGroupData = string.Empty; string strCurrentRowData = string.Empty; int intNewLine = 0; for (int i = 0; i < dtData.Rows.Count; i++) { strNextGroupData = string.Empty; DataRow drRow = dtData.Rows[i]; strCurrentRowData = drRow[strGroupField].ToString(); if (intNewLine == 0) { builder.AppendFormat("<tr><td>{0}</td></tr>", reg.IsMatch(strCurrentRowData) ? "'" + strCurrentRowData : strCurrentRowData); } builder.AppendFormat("<tr>"); foreach (ColumnInfo col in lstHeaders) { if (!col.ColumnName.Equals(strGroupField)) { builder.AppendFormat("<td align='center' valign='middle'>{0}</td>", reg.IsMatch(drRow[col.ColumnName].ToString()) ? "'" + drRow[col.ColumnName].ToString() : drRow[col.ColumnName].ToString()); } } builder.AppendFormat("</tr>"); if (intNewLine == 0) { foreach (ColumnInfo col in lstSumFields) { drRow[string.Format("Total_{0}_{1}", strGroupField, col.ColumnName)] = drRow[col.ColumnName].ToString(); } } else { foreach (ColumnInfo col in lstSumFields) { drRow[string.Format("Total_{0}_{1}", strGroupField, col.ColumnName)] = Convert.ToDouble(dtData.Rows[i - 1][string.Format("Total_{0}_{1}", strGroupField, col.ColumnName)]) + Convert.ToDouble(drRow[col.ColumnName].ToString()); } } if (i == 0) { foreach (ColumnInfo col in lstSumFields) { drRow[string.Format("Total_{0}", col.ColumnName)] = drRow[col.ColumnName].ToString(); } } else { foreach (ColumnInfo col in lstSumFields) { drRow[string.Format("Total_{0}", col.ColumnName)] = Convert.ToDouble(dtData.Rows[i - 1][string.Format("Total_{0}", col.ColumnName)]) + Convert.ToDouble(drRow[col.ColumnName].ToString()); } } intNewLine++; if ((i + 1) < dtData.Rows.Count) { strNextGroupData = dtData.Rows[i + 1][strGroupField].ToString(); } if (!strCurrentRowData.Equals(strNextGroupData)) { AppendLastGroupLine(lstHeaders, lstSumFields, builder, drRow, strGroupField); intNewLine = 0; } } if (dtData.Rows.Count > 0) { AppendLastTotalLine(lstHeaders, lstSumFields, builder, dtData.Rows[dtData.Rows.Count - 1], strGroupField); } GenerateHtmlFooter(builder); return builder.ToString(); } private static void AppendLastGroupLine(List<ColumnInfo> lstHeaders, List<ColumnInfo> lstSumFields, StringBuilder builder, DataRow drRow, string strGroupField) { builder.AppendFormat("<tr>"); for (int i = 0; i < lstHeaders.Count; i++) { ColumnInfo col = lstHeaders[i]; if (col.ColumnName.Equals(strGroupField)) continue; if (lstSumFields.Contains(col)) { builder.AppendFormat("<td align='center' valign='middle'style=\"color:red;\">{0}</td>", drRow[string.Format("Total_{0}_{1}", strGroupField, col.ColumnName)].ToString()); drRow[string.Format("Total_{0}_{1}", strGroupField, col.ColumnName)] = 0; } else { if (i == 0) { builder.AppendFormat("<td>{0}</td>", "小計:"); } else { builder.AppendFormat("<td>{0}</td>", string.Empty); } } } builder.AppendFormat("</tr>"); } private static void AppendLastTotalLine(List<ColumnInfo> lstHeaders, List<ColumnInfo> lstSumFields, StringBuilder builder, DataRow drRow, string strGroupField) { builder.AppendFormat("<tr>"); for (int i = 0; i < lstHeaders.Count; i++) { ColumnInfo col = lstHeaders[i]; if (col.ColumnName.Equals(strGroupField)) continue; if (lstSumFields.Contains(col)) { builder.AppendFormat("<td align='center' valign='middle'style=\"color:red;\">{0}</td>", drRow[string.Format("Total_{0}", col.ColumnName)].ToString()); } else { if (i == 0) { builder.AppendFormat("<td style=\"color:red;\">{0}</td>", "總計:"); } else { builder.AppendFormat("<td>{0}</td>", string.Empty); } } } builder.AppendFormat("</tr>"); } public static void GenerateContent(DataTable dtData, StringBuilder builder, List<ColumnInfo> lstHeaders) { Regex reg = new Regex(@"(^[-0\\+][0-9]+)|(^\d+[-]\d+$)"); foreach (DataRow drRow in dtData.Rows) { builder.AppendFormat("<tr>"); foreach (ColumnInfo col in lstHeaders) { if (dtData.Columns.Contains(col.ColumnName) && col.IsShow) { if (col.ColumnType.ToLower().Equals(Public_ColumnType.BOOLEAN.ToString().ToLower())) { builder.AppendFormat("<td align='center' valign='middle'>{0}</td>", "1".Equals(drRow[col.ColumnName].ToString()) ? "是" : "否"); } else { builder.AppendFormat("<td align='center' {0} valign='middle'>{1}</td>", reg.IsMatch(drRow[col.ColumnName].ToString()) ? "style=\"mso-number-format:'\\@';\"" : "", drRow[col.ColumnName].ToString()); } } } builder.AppendFormat("</tr>"); } } public static void GenerateHtmlHeaderWithoutTable(StringBuilder builder) { builder.AppendFormat(@"<html><head> <!--[if gte mso 9]><xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>工作表标题</x:Name> <x:WorksheetOptions> <x:Print> <x:ValidPrinterInfo /> </x:Print> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml> <![endif]--> <meta http-equiv='Content-Type' content='text/html; charset=big5'> </head> <body>"); } public static void GenerateHtmlHeader(StringBuilder builder) { builder.AppendFormat(@"<html><head> <!--[if gte mso 9]><xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>工作表标题</x:Name> <x:WorksheetOptions> <x:Print> <x:ValidPrinterInfo /> </x:Print> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml> <![endif]--> <meta http-equiv='Content-Type' content='text/html; charset=big5'> </head> <body><table border='1' style='border-collapse:collapse'>"); } public static void GenerateHtmlFooterWithoutTable(StringBuilder builder) { builder.AppendFormat("</body></html>"); } public static void GenerateHtmlFooter(StringBuilder builder) { builder.AppendFormat("</table></body></html>"); } public static void GenerateCaption(StringBuilder builder, DataTable dtData, int colSpan) { if (dtData.ExtendedProperties.ContainsKey("Caption")) { builder.AppendFormat("<tr><td align='center' valign='middle' colspan='{0}'style=\"font-size:large; color:red;\">{1}</td></tr>", colSpan, dtData.ExtendedProperties["Caption"].ToString()); } } public static void GenerateHeader(DataTable dtData, StringBuilder builder, List<ColumnInfo> lstHeaders, List<ColumnInfo> lstExcludes) { builder.AppendFormat("<tr>"); foreach (ColumnInfo col in lstHeaders) { if (dtData.Columns.Contains(col.ColumnName) && col.IsShow) { if (!lstExcludes.Contains(col)) { builder.AppendFormat("<td align='center' valign='middle' style=\"mso-number-format:'\\@';\">{0}</td>", col.ColumnDisplayName); } } } builder.AppendFormat("</tr>"); } public static void Export(XmlNode xml, string fileName, HttpResponse response, HttpServerUtility server) { response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName)); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(server.MapPath("Excel.xsl")); xtExcel.Transform(xml, null, response.OutputStream); response.End(); } public static void ExportExcel(DataTable dt, string strFileName, List<ColumnInfo> lstHeaders) { if (dt == null || dt.Rows.Count == 0) return; HttpResponse response = HttpContext.Current.Response; HttpServerUtility server = HttpContext.Current.Server; SetHeaders(HttpContext.Current.Response, HttpContext.Current.Request, strFileName); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(server.MapPath("Excel.xsl")); string strJson = UtilJson.DataTableToJson(dt, lstHeaders); XmlNode xmlNode = JsonConvert.DeserializeXmlNode("{records:{record:" + strJson + "}}"); xtExcel.Transform(xmlNode, null, response.OutputStream); response.End(); } public static void DataSetToExcel(DataTable dt, string FileName, List<ColumnInfo> lstHeaders) { try { SetHeaders(HttpContext.Current.Response, HttpContext.Current.Request, FileName); StringBuilder colHeaders = new StringBuilder(); StringBuilder Is_item = new StringBuilder(); StringWriter sfw = new StringWriter(); int i = 0; int cl = dt.Columns.Count; for (i = 0; i < lstHeaders.Count; i++) { if (dt.Columns.Contains(lstHeaders[i].ColumnName)) { colHeaders.Append(lstHeaders[i].ColumnDisplayName.Replace("\n", " ").Replace("\r", " ") + "\t"); } } sfw.WriteLine(colHeaders.ToString()); string strValue = string.Empty; string strType = string.Empty; Regex reg = new Regex(@"(^0[0-9]+)|(^\d+[-]\d+$)"); foreach (DataRow row in dt.Rows) { for (i = 0; i < lstHeaders.Count; i++) { if (dt.Columns.Contains(lstHeaders[i].ColumnName.ToString())) { strValue = row[lstHeaders[i].ColumnName].ToString(); strType = dt.Columns[lstHeaders[i].ColumnName].DataType.FullName; if (reg.IsMatch(strValue)) { Is_item.Append("'" + strValue.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ") + "\t"); } else { Is_item.Append(strValue.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ") + "\t"); } } } sfw.WriteLine(Is_item); Is_item = new StringBuilder(); } HttpContext.Current.Response.Write(sfw.ToString()); HttpContext.Current.Response.End(); } catch (Exception e) { throw e; } } public static void DataSetToExcel(DataSet ds, string FileName, List<ColumnInfo> lstHeaders) { DataSetToExcel(ds.Tables[0], FileName, lstHeaders); } public static DataSet GetDataFromExcel(string strExcelFile, string strSql) { string strConn = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';", strExcelFile); DataSet ds = new DataSet(); using (OleDbConnection conn = new OleDbConnection(strConn)) { conn.Open(); using (OleDbDataAdapter adapter = new OleDbDataAdapter(strSql, strConn)) { adapter.Fill(ds); } } return ds; } public static int ExecuteNonQuery(string strExcelFile, string strSql) { string strConn = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';", strExcelFile); OleDbCommand cmd = new OleDbCommand(); using (OleDbConnection conn = new OleDbConnection(strConn)) { if (!conn.State.Equals(ConnectionState.Open)) { conn.Open(); } cmd.Connection = conn; cmd.CommandText = strSql; cmd.CommandType = CommandType.Text; int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } } |