当前位置:   article > 正文

导入导出excel

导入导出excel

调用Office组件

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using ZG.ERP.App.AppPublic;
  9. using ZG.ERP.Common.SysParameter;
  10. using ZG.ERP.Common.Data;
  11. using ZG.ERP.Common.Utility;
  12. using System.IO;
  13. using System.Diagnostics;
  14. using System.Data.OleDb;
  15. using System.Runtime.InteropServices;
  16. //打开并读取Excel模板
  17. Microsoft.Office.Interop.Excel.Application application; //这是一个客户端
  18. Microsoft.Office.Interop.Excel.Workbooks workbooks; //所有工作薄
  19. Microsoft.Office.Interop.Excel.Worksheet worksheet;//工作表
  20. Microsoft.Office.Interop.Excel.Workbook workbook; //所用到的工作表
  21. application = new Microsoft.Office.Interop.Excel.Application();
  22. try
  23. {
  24. workbooks = application.Workbooks;
  25. workbook = workbooks.Open(
  26. filePath, Type.Missing, Type.Missing,
  27. Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  28. Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
  29. Type.Missing, Type.Missing);
  30. worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
  31. Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, 1];
  32. //dtExcelData.Columns.Add("SKU编号");
  33. dtExcelData.Columns.Add("品名");
  34. dtExcelData.Columns.Add("材质");
  35. dtExcelData.Columns.Add("钢厂");
  36. dtExcelData.Columns.Add("规格");
  37. dtExcelData.Columns.Add("预定数量(件)");
  38. dtExcelData.Columns.Add("预定重量(吨)");
  39. dtExcelData.Columns.Add("预付单价(元)");
  40. dtExcelData.Columns.Add("预付款小计(元)");
  41. dtExcelData.Columns.Add("备注");
  42. string productName;
  43. string material;
  44. string factory;
  45. string specification;
  46. string FLAN_num;
  47. string Quantity;
  48. string FLAN_price;
  49. string totalPiece;
  50. string remark;
  51. //循环读取Excel内容放入DataTable
  52. for (int i = 2; i <= worksheet.UsedRange.Rows.Count; i++)
  53. {
  54. if (((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 2]).Value2 == null)
  55. {
  56. continue;
  57. }
  58. productName = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 1]).Value2 != null ?
  59. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 1]).Value2.ToString() : string.Empty;
  60. material = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 2]).Value2 != null ?
  61. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 2]).Value2.ToString() : string.Empty;
  62. factory = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 3]).Value2 != null ?
  63. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 3]).Value2.ToString() : string.Empty;
  64. specification = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 4]).Value2 != null ?
  65. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 4]).Value2.ToString() : string.Empty;
  66. Quantity = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 5]).Value2 != null ?
  67. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 5]).Value2.ToString() : string.Empty;
  68. FLAN_num = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 6]).Value2 != null ?
  69. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 6]).Value2.ToString() : string.Empty;
  70. FLAN_price = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 7]).Value2 != null ?
  71. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 7]).Value2.ToString() : string.Empty;
  72. totalPiece = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 8]).Value2 != null ?
  73. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 8]).Value2.ToString() : string.Empty;
  74. remark = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 9]).Value2 != null ?
  75. ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[i, 9]).Value2.ToString() : string.Empty;
  76. dtExcelData.Rows.Add(new object[] { productName, material,factory, specification,Quantity, FLAN_num,
  77. FLAN_price, totalPiece, remark});
  78. }
  79. workbook.Close(Type.Missing, filePath, Type.Missing);
  80. workbooks.Close();
  81. }
  82. catch { }
  83. finally
  84. {
  85. application.Quit();
  86. //杀Excel进程
  87. IntPtr t = new IntPtr(application.Hwnd); //得到这个句柄,具体作用是得到这块内存入口
  88. int k = 0;
  89. GetWindowThreadProcessId(t, out k); //得到本进程唯一标志k
  90. System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到对进程k的引用
  91. p.Kill(); //关闭进程k
  92. }

 

第二种,利用NPOI开源组件导入导出

 

  1. //===============================================================================
  2. //功 能:NPOI开源组件导出导入EXCEL
  3. //作 者:段晓锋
  4. //创建日期:2011年11月11日
  5. //修改历史
  6. //修 改 人:
  7. //修改日期:
  8. //修改描述:
  9. //===============================================================================
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Text;
  14. using System.IO;
  15. using System.Data;
  16. using ZG.ERP.Common.SysParameter;
  17. using ZG.ERP.Common.Data;
  18. using ZG.ERP.Common.Utility;
  19. using NPOI;
  20. using NPOI.HPSF;
  21. using NPOI.HSSF;
  22. using NPOI.POIFS;
  23. using NPOI.HSSF.Util;
  24. using NPOI.SS.UserModel;
  25. using NPOI.HSSF.UserModel;
  26. using NPOI.Util;
  27. namespace ZG.ERP.Common.Utility
  28. {
  29. /// <summary>
  30. /// NPOI导出导入帮助类
  31. /// </summary>
  32. public class NPOIHelper
  33. {
  34. #region NPOI开源组件导出EXCEL方法
  35. /// <summary>
  36. /// DataTable导出到Excel的MemoryStream
  37. /// </summary>
  38. /// <param name="dtSource">源DataTable</param>
  39. /// <param name="strHeaderText">表头文本</param>
  40. public static MemoryStream Export(DataTable dtSource, string strHeaderText, out string errorstr)
  41. {
  42. errorstr = "";
  43. try
  44. {
  45. HSSFWorkbook workbook = new HSSFWorkbook();
  46. ISheet sheet = workbook.CreateSheet();
  47. #region 右击文件 属性信息
  48. {
  49. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  50. dsi.Company = "NPOI";
  51. workbook.DocumentSummaryInformation = dsi;
  52. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  53. si.Author = "找钢网"; //填加xls文件作者信息
  54. si.ApplicationName = "找钢网ERP"; //填加xls文件创建程序信息
  55. si.LastAuthor = SysConfig.LoginUserInfo.LoginName; //填加xls文件最后保存者信息
  56. si.Comments = SysConfig.LoginUserInfo.LoginName; //填加xls文件作者信息
  57. si.Title = "找钢网"; //填加xls文件标题信息
  58. si.Subject = "找钢网的码单表格";//填加文件主题信息
  59. si.CreateDateTime = DateTime.Now;
  60. workbook.SummaryInformation = si;
  61. }
  62. #endregion
  63. //取得列宽
  64. int[] arrColWidth = new int[dtSource.Columns.Count];
  65. foreach (DataColumn item in dtSource.Columns)
  66. {
  67. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  68. }
  69. for (int i = 0; i < dtSource.Rows.Count; i++)
  70. {
  71. for (int j = 0; j < dtSource.Columns.Count; j++)
  72. {
  73. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  74. if (intTemp > arrColWidth[j])
  75. {
  76. arrColWidth[j] = intTemp;
  77. }
  78. }
  79. }
  80. int rowIndex = 0;
  81. IRow row0 = sheet.CreateRow(0);//在工作表中添加一行
  82. ICellStyle headStyle = workbook.CreateCellStyle();
  83. //headStyle.Alignment =CellHorizontalAlignment.CENTER;
  84. IFont font = workbook.CreateFont();
  85. font.FontHeightInPoints = 10;
  86. font.Boldweight = 700;
  87. headStyle.SetFont(font);
  88. foreach (DataColumn column in dtSource.Columns)
  89. {
  90. row0.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  91. row0.GetCell(column.Ordinal).CellStyle = headStyle;
  92. //设置列宽
  93. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  94. }
  95. rowIndex = 1;
  96. foreach (DataRow row in dtSource.Rows)
  97. {
  98. //#region 新建表,填充表头,填充列头,样式
  99. //if (rowIndex == 65535 || rowIndex == 0)
  100. //{
  101. // if (rowIndex != 0)
  102. // {
  103. // sheet = workbook.CreateSheet();
  104. // }
  105. // rowIndex = 2;
  106. //}
  107. //#endregion
  108. #region 填充内容
  109. IRow dataRow = sheet.CreateRow(rowIndex);
  110. foreach (DataColumn column in dtSource.Columns)
  111. {
  112. ICell newCell = dataRow.CreateCell(column.Ordinal);
  113. string drValue = row[column].ToString();
  114. switch (column.DataType.ToString())
  115. {
  116. case "System.String"://字符串类型
  117. newCell.SetCellValue(drValue);
  118. break;
  119. case "System.DateTime"://日期类型
  120. DateTime dateV;
  121. DateTime.TryParse(drValue, out dateV);
  122. newCell.SetCellValue(dateV);
  123. break;
  124. case "System.Boolean"://布尔型
  125. bool boolV = false;
  126. bool.TryParse(drValue, out boolV);
  127. newCell.SetCellValue(boolV);
  128. break;
  129. case "System.Int16"://整型
  130. case "System.Int32":
  131. case "System.Int64":
  132. case "System.Byte":
  133. int intV = 0;
  134. int.TryParse(drValue, out intV);
  135. newCell.SetCellValue(intV);
  136. break;
  137. case "System.Decimal"://浮点型
  138. case "System.Double":
  139. double doubV = 0;
  140. double.TryParse(drValue, out doubV);
  141. newCell.SetCellValue(doubV);
  142. break;
  143. case "System.DBNull"://空值处理
  144. newCell.SetCellValue("");
  145. break;
  146. default:
  147. newCell.SetCellValue("");
  148. break;
  149. }
  150. }
  151. #endregion
  152. rowIndex++;
  153. }
  154. using (MemoryStream ms = new MemoryStream())
  155. {
  156. workbook.Write(ms);
  157. ms.Flush();
  158. ms.Position = 0;
  159. //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
  160. return ms;
  161. }
  162. }
  163. catch(Exception ex)
  164. {
  165. errorstr = ex.Message.ToString();
  166. return null;
  167. }
  168. }
  169. #endregion
  170. #region NPOI开源组件导入EXCEL方法
  171. /// <summary>
  172. /// xls导入到datatable
  173. /// </summary>
  174. /// <param name="dtSource">源DataTable</param>
  175. /// <param name="strHeaderText">表头文本</param>
  176. public static DataTable Import(string filePath, out string errorStr)
  177. {
  178. try
  179. {
  180. errorStr = "";
  181. HSSFWorkbook hssfworkbook;
  182. using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  183. {
  184. hssfworkbook = new HSSFWorkbook(file);
  185. }
  186. ISheet sheet = hssfworkbook.GetSheetAt(0);
  187. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  188. DataTable dt = new DataTable();
  189. for (int j = 0; j < 12; j++)
  190. {
  191. dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString());
  192. }
  193. while (rows.MoveNext())
  194. {
  195. IRow row = (HSSFRow)rows.Current;
  196. DataRow dr = dt.NewRow();
  197. for (int i = 0; i < row.LastCellNum; i++)
  198. {
  199. ICell cell = row.GetCell(i);
  200. if (cell == null)
  201. {
  202. dr[i] = null;
  203. }
  204. else
  205. {
  206. dr[i] = cell.ToString();
  207. }
  208. }
  209. dt.Rows.Add(dr);
  210. }
  211. return dt;
  212. }
  213. catch(Exception ex)
  214. {
  215. errorStr = ex.Message.ToString();
  216. return null;
  217. }
  218. }
  219. #endregion
  220. }
  221. }

 

  NPOI开源地址:http://npoi.codeplex.com/

 
  MyXls开源地址: http://sourceforge.net/projects/myxls/
 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/216109
推荐阅读
相关标签
  

闽ICP备14008679号