C# EF ExcelHelper 导入导出

举报
清雨小竹 发表于 2022/09/25 00:24:08 2022/09/25
【摘要】 //EF导出示例 var query = from u in orderQuery join pro in dbContext.Project on u.projectNo equals pro.projectNo join org in dbContext.Org on u.orgNo equ...


  
  1. //EF导出示例
  2. var query = from u in orderQuery
  3. join pro in dbContext.Project on
  4. u.projectNo equals pro.projectNo
  5. join org in dbContext.Org on
  6. u.orgNo equals org.orgNo into JoinedEmpDept
  7. from dept in JoinedEmpDept.DefaultIfEmpty()
  8. select new
  9. {
  10. 学校名称= pro.projectName,
  11. 所属班级=dept.orgName,
  12. 费用类型=u.orderName,
  13. 学生姓名=u.userName,
  14. 身份证号=u.userNo,
  15. 手机号=u.userPhone,
  16. 订单编号=u.orderNo,
  17. 费用金额=u.orderAmount/100.0,
  18. 支付状态=u.payState==1?"已支付":"未支付",
  19. 支付时间=u.payTime,
  20. 银行流水号=u.ccbOrderId,
  21. 添加时间=u.createTime,
  22. 备注=u.remark
  23. };
  24. string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  25. string file = localPath + fileName;
  26. using (ExcelHelper excelHelper = new ExcelHelper(file))
  27. {
  28. var list = query.OrderByDescending(u => u.添加时间).ToList();
  29. excelHelper.ListToExcel(list,"费用");
  30. return ReturnNode.ReturnSuccess(fileName);
  31. }

  
  1. //EF导出示例2,SQL直接导出
  2. try
  3. {
  4. var sql = "SELECT * from user ";
  5. //输出排名
  6. //sql = string.Format("SELECT @rank :=@rank + 1 AS 排名,A.* FROM ( {0}) A, (SELECT @rank := 0) B;", sql);
  7. string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
  8. string file = localPath + fileName;
  9. using (ExcelHelper excelHelper = new ExcelHelper(file))
  10. {
  11. System.Data.Common.DbCommand cmd = dbContext.Database.Connection.CreateCommand();
  12. cmd.CommandText = sql;
  13. cmd.CommandType = CommandType.Text;
  14. //转成sqlcommand正常查询语句。
  15. MySql.Data.MySqlClient.MySqlDataAdapter da = new MySql.Data.MySqlClient.MySqlDataAdapter();
  16. da.SelectCommand = cmd as MySql.Data.MySqlClient.MySqlCommand;
  17. DataTable dt = new DataTable();
  18. da.Fill(dt);
  19. excelHelper.DataTableToExcel(dt, "用户表",true);
  20. return ReturnNode.ReturnSuccess(serverPath + fileName);
  21. }
  22. }
  23. catch (Exception ex)
  24. {
  25. return ReturnNode.ReturnError(ex.Message);
  26. }


  
  1. //导入示例
  2. string file = "C:\\Data\\模板.xlsx";
  3. using (ExcelHelper excelHelper = new ExcelHelper(file))
  4. {
  5. DataTable dt = excelHelper.ExcelToDataTable("Sheet1", true);
  6. int num = 0;
  7. for (int i = 0; i < dt.Rows.Count; ++i)
  8. {
  9. DataRow row = dt.Rows[i];
  10. string index = row[0].ToString();
  11. string orgName = row[1].ToString();
  12. string orgNo = row[2].ToString();
  13. string orderName = row[3].ToString();
  14. string orderAmount = row[4].ToString();
  15. string userName = row[5].ToString();
  16. string userNo = row[6].ToString();
  17. string userPhone = row[7].ToString();
  18. string remark = row[8].ToString();
  19. num++;
  20. }
  21. }


  
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.XSSF.UserModel;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.ComponentModel;
  7. using System.Data;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace YFAPICommon.Lib
  14. {
  15. class ExcelHelper : IDisposable
  16. {
  17. private string fileName = null; //文件名
  18. private NPOI.SS.UserModel.IWorkbook workbook = null;
  19. private FileStream fs = null;
  20. private bool disposed;
  21. public ExcelHelper(string fileName)
  22. {
  23. this.fileName = fileName;
  24. disposed = false;
  25. }
  26. /// <summary>
  27. /// 将DataTable数据导入到excel中
  28. /// </summary>
  29. /// <param name="data">要导入的数据</param>
  30. /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
  31. /// <param name="sheetName">要导入的excel的sheet的名称</param>
  32. /// <returns>导入数据行数(包含列名那一行)</returns>
  33. public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
  34. {
  35. int i = 0;
  36. int j = 0;
  37. int count = 0;
  38. ISheet sheet = null;
  39. fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  40. if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  41. workbook = new XSSFWorkbook();
  42. else if (fileName.IndexOf(".xls") > 0) // 2003版本
  43. workbook = new HSSFWorkbook();
  44. try
  45. {
  46. if (workbook != null)
  47. {
  48. sheet = workbook.CreateSheet(sheetName);
  49. }
  50. else
  51. {
  52. return -1;
  53. }
  54. if (isColumnWritten == true) //写入DataTable的列名
  55. {
  56. IRow row = sheet.CreateRow(0);
  57. for (j = 0; j < data.Columns.Count; ++j)
  58. {
  59. row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
  60. }
  61. count = 1;
  62. }
  63. else
  64. {
  65. count = 0;
  66. }
  67. for (i = 0; i < data.Rows.Count; ++i)
  68. {
  69. IRow row = sheet.CreateRow(count);
  70. for (j = 0; j < data.Columns.Count; ++j)
  71. {
  72. row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
  73. }
  74. ++count;
  75. }
  76. workbook.Write(fs); //写入到excel
  77. return count;
  78. }
  79. catch (Exception ex)
  80. {
  81. Console.WriteLine("Exception: " + ex.Message);
  82. return -1;
  83. }
  84. }
  85. /// <summary>
  86. /// 将List数据导入到excel中
  87. /// </summary>
  88. /// <param name="data">要导入的数据</param>
  89. /// <param name="sheetName">要导入的excel的sheet的名称</param>
  90. /// <returns>导入数据行数(包含列名那一行)</returns>
  91. public int ListToExcel<T>(List<T> data, string sheetName)
  92. {
  93. ISheet sheet = null;
  94. fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  95. if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  96. workbook = new XSSFWorkbook();
  97. else if (fileName.IndexOf(".xls") > 0) // 2003版本
  98. workbook = new HSSFWorkbook();
  99. try
  100. {
  101. if (workbook != null)
  102. {
  103. sheet = workbook.CreateSheet(sheetName);
  104. }
  105. else
  106. {
  107. return -1;
  108. }
  109. PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
  110. IRow row0 = sheet.CreateRow(0);
  111. for (int i = 0; i < properties.Count; i++)
  112. {
  113. PropertyDescriptor property = properties[i];
  114. Debug.WriteLine(property.Name);
  115. row0.CreateCell(i).SetCellValue(property.Name);
  116. }
  117. int count = 1;
  118. object[] values = new object[properties.Count];
  119. foreach (T item in data)
  120. {
  121. IRow row = sheet.CreateRow(count);
  122. for (int j = 0; j < values.Length; j++)
  123. {
  124. object obj = properties[j].GetValue(item);
  125. Debug.WriteLine(properties[j].GetValue(item));
  126. row.CreateCell(j).SetCellValue(obj==null?"":obj.ToString());
  127. }
  128. ++count;
  129. }
  130. workbook.Write(fs); //写入到excel
  131. return count;
  132. }
  133. catch (Exception ex)
  134. {
  135. Console.WriteLine("Exception: " + ex.Message);
  136. return -1;
  137. }
  138. }
  139. /// <summary>
  140. /// 将excel中的数据导入到DataTable中
  141. /// </summary>
  142. /// <param name="sheetName">excel工作薄sheet的名称</param>
  143. /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  144. /// <returns>返回的DataTable</returns>
  145. public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
  146. {
  147. ISheet sheet = null;
  148. DataTable data = new DataTable();
  149. int startRow = 0;
  150. try
  151. {
  152. fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  153. if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  154. workbook = new XSSFWorkbook(fs);
  155. else if (fileName.IndexOf(".xls") > 0) // 2003版本
  156. workbook = new HSSFWorkbook(fs);
  157. if (sheetName != null)
  158. {
  159. sheet = workbook.GetSheet(sheetName);
  160. if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  161. {
  162. sheet = workbook.GetSheetAt(0);
  163. }
  164. }
  165. else
  166. {
  167. sheet = workbook.GetSheetAt(0);
  168. }
  169. if (sheet != null)
  170. {
  171. IRow firstRow = sheet.GetRow(0);
  172. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  173. if (isFirstRowColumn)
  174. {
  175. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  176. {
  177. ICell cell = firstRow.GetCell(i);
  178. if (cell != null)
  179. {
  180. string cellValue = cell.StringCellValue;
  181. if (cellValue != null)
  182. {
  183. DataColumn column = new DataColumn(cellValue);
  184. data.Columns.Add(column);
  185. }
  186. }
  187. }
  188. startRow = sheet.FirstRowNum + 1;
  189. }
  190. else
  191. {
  192. startRow = sheet.FirstRowNum;
  193. }
  194. //最后一列的标号
  195. int rowCount = sheet.LastRowNum;
  196. for (int i = startRow; i <= rowCount; ++i)
  197. {
  198. IRow row = sheet.GetRow(i);
  199. if (row == null)
  200. break;
  201. //continue; //没有数据的行默认是null       
  202. DataRow dataRow = data.NewRow();
  203. for (int j = row.FirstCellNum; j < cellCount; ++j)
  204. {
  205. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  206. dataRow[j] = row.GetCell(j).ToString();
  207. }
  208. data.Rows.Add(dataRow);
  209. }
  210. }
  211. return data;
  212. }
  213. catch (Exception ex)
  214. {
  215. Console.WriteLine("Exception: " + ex.Message);
  216. //System.Windows.Forms.MessageBox.Show(ex.Message);
  217. return null;
  218. }
  219. }
  220. internal void ListToExcel(List<object> list, string v)
  221. {
  222. throw new NotImplementedException();
  223. }
  224. public void Dispose()
  225. {
  226. Dispose(true);
  227. GC.SuppressFinalize(this);
  228. }
  229. protected virtual void Dispose(bool disposing)
  230. {
  231. if (!this.disposed)
  232. {
  233. if (disposing)
  234. {
  235. if (fs != null)
  236. fs.Close();
  237. }
  238. fs = null;
  239. disposed = true;
  240. }
  241. }
  242. }
  243. }

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/95599785

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。