颐和api

ExcelHelper.cs 3.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using Microsoft.AspNetCore.Http;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using OfficeOpenXml;
  10. namespace MadRunFabric.Common
  11. {
  12. public interface IFormFile
  13. {
  14. string ContentType { get; }
  15. string ContentDisposition { get; }
  16. IHeaderDictionary Headers { get; }
  17. long Length { get; }
  18. string Name { get; }
  19. string FileName { get; }
  20. Stream OpenReadStream();
  21. void CopyTo(Stream target);
  22. Task CopyToAsync(Stream target, CancellationToken cancellationToken);
  23. }
  24. public class ExcelHelper
  25. {
  26. /// <summary>
  27. /// 导入Excel
  28. /// </summary>
  29. /// <param name="filepath"></param>
  30. /// <param name="filename"></param>
  31. /// <param name="excelfile"></param>
  32. /// <returns></returns>
  33. public DataTable ImportExcel(string filepath, string filename, FileStream excelfile)
  34. {
  35. //string sWebRootFolder = _hostingEnvironment.WebRootPath;
  36. //string sFileName = $"{Guid.NewGuid()}.xlsx";
  37. FileInfo file = new FileInfo(Path.Combine(filepath, filename));
  38. DataTable dt = new DataTable();
  39. try
  40. {
  41. using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
  42. {
  43. excelfile.CopyTo(fs);
  44. fs.Flush();
  45. }
  46. using (ExcelPackage package = new ExcelPackage(file))
  47. {
  48. //StringBuilder sb = new StringBuilder();
  49. ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
  50. int rowCount = worksheet.Dimension.Rows;
  51. int ColCount = worksheet.Dimension.Columns;
  52. for (int col = 1; col <= ColCount; col++)
  53. {
  54. dt.Columns.Add(worksheet.Cells[1, col].Value.ToString());
  55. }
  56. //bool bHeaderRow = true;
  57. for (int row = 2; row <= rowCount; row++)
  58. {
  59. for (int col = 1; col <= ColCount; col++)
  60. {
  61. dt.Rows[row - 1][col - 1] = worksheet.Cells[row, col].Value.ToString();
  62. //if (bHeaderRow)
  63. //{
  64. // sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  65. //}
  66. //else
  67. //{
  68. //sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  69. //}
  70. }
  71. //sb.Append(Environment.NewLine);
  72. //bHeaderRow = false;
  73. }
  74. return dt;// Content(sb.ToString());
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. return null;
  80. }
  81. }
  82. }
  83. }