dateTable导出到excel的MemoryStream

  1. /// <summary>
  2. /// DataTable导出到Excel的MemoryStream Export()
  3. /// </summary>
  4. /// <param name="dtSource">DataTable数据源</param>
  5. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  6. /// <param name="isRemoveColumns"></param>
  7. public static MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig, bool isRemoveColumns = false)
  8. {
  9. if (isRemoveColumns)
  10. {
  11. int colint = ;
  12. for (int i = ; i < dtSource.Columns.Count; )
  13. {
  14. DataColumn column = dtSource.Columns[i];
  15. if (colint>=excelConfig.ColumnEntity.Count || excelConfig.ColumnEntity[colint].Column != column.ColumnName)
  16. {
  17. dtSource.Columns.Remove(column.ColumnName);
  18. }
  19. else
  20. {
  21. ColumnEntity columnentity = excelConfig.ColumnEntity.Find(t => t.Column == dtSource.Columns[i].ColumnName);
  22. dtSource.Columns[i].ColumnName = columnentity.ExcelColumn;//修改列头名
  23. i++;
  24. colint++;
  25. }
  26.  
  27. }
  28. }
  29.  
  30. HSSFWorkbook workbook = new HSSFWorkbook();
  31. ISheet sheet = workbook.CreateSheet();
  32.  
  33. #region 右击文件 属性信息
  34. {
  35. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  36. dsi.Company = "NPOI";
  37. workbook.DocumentSummaryInformation = dsi;
  38.  
  39. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  40. si.Author = "zdd"; //填加xls文件作者信息
  41. si.ApplicationName = "XX系统"; //填加xls文件创建程序信息
  42. si.LastAuthor = "zdd"; //填加xls文件最后保存者信息
  43. si.Comments = "zdd"; //填加xls文件作者信息
  44. si.Title = "标题信息"; //填加xls文件标题信息
  45. si.Subject = "主题信息";//填加文件主题信息
  46. si.CreateDateTime = System.DateTime.Now;
  47. workbook.SummaryInformation = si;
  48. }
  49. #endregion
  50.  
  51. #region 设置标题样式
  52. ICellStyle headStyle = workbook.CreateCellStyle();
  53. int[] arrColWidth = new int[dtSource.Columns.Count];
  54. string[] arrColName = new string[dtSource.Columns.Count];//列名
  55. ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
  56. headStyle.Alignment = HorizontalAlignment.Center; // ------------------
  57. if (excelConfig.Background != new Color())
  58. {
  59. if (excelConfig.Background != new Color())
  60. {
  61. headStyle.FillPattern = FillPattern.SolidForeground;
  62. headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
  63. }
  64. }
  65. IFont font = workbook.CreateFont();
  66. font.FontHeightInPoints = excelConfig.TitlePoint;
  67. if (excelConfig.ForeColor != new Color())
  68. {
  69. font.Color = GetXLColour(workbook, excelConfig.ForeColor);
  70. }
  71. font.Boldweight = ;
  72. headStyle.SetFont(font);
  73. #endregion
  74.  
  75. #region 列头及样式
  76. ICellStyle cHeadStyle = workbook.CreateCellStyle();
  77. cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
  78. IFont cfont = workbook.CreateFont();
  79. cfont.FontHeightInPoints = excelConfig.HeadPoint;
  80. cHeadStyle.SetFont(cfont);
  81. #endregion
  82.  
  83. #region 设置内容单元格样式
  84. foreach (DataColumn item in dtSource.Columns)
  85. {
  86. ICellStyle columnStyle = workbook.CreateCellStyle();
  87. columnStyle.Alignment = HorizontalAlignment.Center;
  88. arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
  89. arrColName[item.Ordinal] = item.ColumnName.ToString();
  90. if (excelConfig.ColumnEntity != null)
  91. {
  92. ColumnEntity columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName);
  93. if (columnentity != null)
  94. {
  95. arrColName[item.Ordinal] = columnentity.ExcelColumn;
  96. if (columnentity.Width != )
  97. {
  98. arrColWidth[item.Ordinal] = columnentity.Width;
  99. }
  100. if (columnentity.Background != new Color())
  101. {
  102. if (columnentity.Background != new Color())
  103. {
  104. columnStyle.FillPattern = FillPattern.SolidForeground;
  105. columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
  106. }
  107. }
  108. if (columnentity.Font != null || columnentity.Point != || columnentity.ForeColor != new Color())
  109. {
  110. IFont columnFont = workbook.CreateFont();
  111. columnFont.FontHeightInPoints = ;
  112. if (columnentity.Font != null)
  113. {
  114. columnFont.FontName = columnentity.Font;
  115. }
  116. if (columnentity.Point != )
  117. {
  118. columnFont.FontHeightInPoints = columnentity.Point;
  119. }
  120. if (columnentity.ForeColor != new Color())
  121. {
  122. columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
  123. }
  124. columnStyle.SetFont(font);
  125. }
  126. columnStyle.Alignment = getAlignment(columnentity.Alignment);
  127. }
  128. }
  129. arryColumStyle[item.Ordinal] = columnStyle;
  130. }
  131. if (excelConfig.IsAllSizeColumn)
  132. {
  133. #region 根据列中最长列的长度取得列宽
  134. for (int i = ; i < dtSource.Rows.Count; i++)
  135. {
  136. for (int j = ; j < dtSource.Columns.Count; j++)
  137. {
  138. if (arrColWidth[j] != )
  139. {
  140. int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
  141. if (intTemp > arrColWidth[j])
  142. {
  143. arrColWidth[j] = intTemp;
  144. }
  145. }
  146.  
  147. }
  148. }
  149. #endregion
  150. }
  151. #endregion
  152.  
  153. #region 填充数据
  154.  
  155. #endregion
  156.  
  157. ICellStyle dateStyle = workbook.CreateCellStyle();
  158. IDataFormat format = workbook.CreateDataFormat();
  159. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  160. int rowIndex = ;
  161. foreach (DataRow row in dtSource.Rows)
  162. {
  163. #region 新建表,填充表头,填充列头,样式
  164. if (rowIndex == || rowIndex == )
  165. {
  166. if (rowIndex != )
  167. {
  168. sheet = workbook.CreateSheet();
  169. }
  170.  
  171. #region 表头及样式
  172. {
  173. if (excelConfig.Title != null)
  174. {
  175. IRow headerRow = sheet.CreateRow();
  176. if (excelConfig.TitleHeight != )
  177. {
  178. headerRow.Height = (short)(excelConfig.TitleHeight * );
  179. }
  180. headerRow.HeightInPoints = ;
  181. headerRow.CreateCell().SetCellValue(excelConfig.Title);
  182. headerRow.GetCell().CellStyle = headStyle;
  183. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , dtSource.Columns.Count - )); // ------------------
  184. }
  185.  
  186. }
  187. #endregion
  188.  
  189. #region 列头及样式
  190. {
  191. IRow headerRow = sheet.CreateRow();
  192. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  193. foreach (DataColumn column in dtSource.Columns)
  194. {
  195. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  196. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  197. //设置列宽
  198. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + ) * );
  199. }
  200. #endregion
  201. }
  202. #endregion
  203.  
  204. rowIndex = ;
  205. }
  206. #endregion
  207.  
  208. #region 填充内容
  209. IRow dataRow = sheet.CreateRow(rowIndex);
  210.  
  211. foreach (DataColumn column in dtSource.Columns)
  212. {
  213. ICell newCell = dataRow.CreateCell(column.Ordinal);
  214. newCell.CellStyle = arryColumStyle[column.Ordinal];
  215. string drValue = row[column].ToString();
  216.  
  217. //如果是图片列
  218. if (column.ToString() == "图片")
  219. {
  220.  
  221. string tPath = DirFileHelper.MapPath("/ExportFile/ImageFiles/");//服务器图片存储目录
  222. if (!DirFileHelper.IsExistDirectory(tPath))//判断是否存在此目录 无则创建
  223. {
  224. DirFileHelper.CreateDir("/ExportFile/ImageFiles/");//创建临时存储压缩后图片路径
  225. }
  226. string filePath = SharedImagePath + drValue;
  227. string newImagePath = tPath + drValue;//压缩后图片绝对路径
  228. if (DirFileHelper.IsExistFile(newImagePath))//若果本地已存在 则不从100共享盘中取图片
  229. {
  230. byte[] bytes = System.IO.File.ReadAllBytes(newImagePath);
  231. int pictureIndex = workbook.AddPicture(bytes, PictureType.JPEG);
  232. HSSFPatriarch par = sheet.CreateDrawingPatriarch() as HSSFPatriarch;
  233.  
  234. HSSFClientAnchor anchor = new HSSFClientAnchor
  235. {
  236. Dx1 = ,//起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
  237. Dy1 = ,//起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
  238. Dx2 = ,//终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
  239. Dy2 = ,//:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
  240. Col1 = column.Ordinal +, //批注起始位置的纵坐标(当前单元格位置+2)
  241. Col2 = column.Ordinal + , //批注结束位置的纵坐标
  242. Row1 = column.Ordinal + , //批注起始位置的横坐标
  243. Row2 = column.Ordinal + //批注结束位置的横坐标
  244. };
  245. HSSFComment comment = par.CreateComment(anchor);
  246. comment.SetBackgroundImage(pictureIndex);
  247. newCell.CellComment = comment;
  248. }
  249. else//取100共享盘图片并压缩指定大小
  250. {
  251. if (DirFileHelper.IsExistFile(filePath))//需要增加判断是否存在此图片
  252. {
  253. ImageHelper.CreateMinImageAndDel(filePath, , , tPath);//压缩指定大小图片
  254. byte[] bytes = System.IO.File.ReadAllBytes(newImagePath);
  255. int pictureIndex = workbook.AddPicture(bytes, PictureType.JPEG);
  256. HSSFPatriarch par = sheet.CreateDrawingPatriarch() as HSSFPatriarch;
  257. HSSFClientAnchor anchor = new HSSFClientAnchor
  258. {
  259. Dx1 = ,//起始单元格的x偏移量,如例子中的255表示直线起始位置距A1单元格左侧的距离;
  260. Dy1 = ,//起始单元格的y偏移量,如例子中的125表示直线起始位置距A1单元格上侧的距离;
  261. Dx2 = ,//终止单元格的x偏移量,如例子中的1023表示直线起始位置距C3单元格左侧的距离;
  262. Dy2 = ,//:终止单元格的y偏移量,如例子中的150表示直线起始位置距C3单元格上侧的距离;
  263. Col1 = column.Ordinal + , //批注起始位置的纵坐标(当前单元格位置+2)
  264. Col2 = column.Ordinal + , //批注结束位置的纵坐标
  265. Row1 = column.Ordinal + , //批注起始位置的横坐标
  266. Row2 = column.Ordinal + //批注结束位置的横坐标
  267. };
  268. HSSFComment comment = par.CreateComment(anchor);
  269. comment.SetBackgroundImage(pictureIndex);
  270. }
  271. }
  272. //newCell.SetCellValue(drValue);
  273. SetCell(newCell, dateStyle, column.DataType, drValue);
  274. }
  275. else
  276. {
  277. SetCell(newCell, dateStyle, column.DataType, drValue);
  278. }
  279.  
  280. }
  281. #endregion
  282. rowIndex++;
  283. }
  284. using (MemoryStream ms = new MemoryStream())
  285. {
  286. workbook.Write(ms);
  287. ms.Flush();
  288. ms.Position = ;
  289. return ms;
  290. }
  291. }
  292. #endregion

NOPI Excel插件导入导出 图片批注的更多相关文章

  1. OpenXml Excel数据导入导出(含图片的导入导出)

    声明:里面的很多东西是基于前人的基础上实现的,具体是哪些人 俺忘了,我做了一些整合和加工 这个项目居于openxml做Excel的导入导出,可以用OpenXml读取Excel中的图片 和OpenXml ...

  2. poi实现excel的导入导出功能

    Java使用poi实现excel的导入导出功能: 工具类ExcelUtil,用于解析和初始化excel的数据:代码如下 package com.raycloud.kmmp.item.service.u ...

  3. NPOI 在指定单元格导入导出图片

    NPOI 在指定单元格导入导出图片 Intro 我维护了一个 NPOI 的扩展,主要用来导入导出 Excel 数据,最近有网友提出了导入 Excel 的时候解析图片的需求,于是就有了本文的探索 导入E ...

  4. excel的导入导出的实现

    1.创建Book类,并编写set方法和get方法 package com.bean; public class Book { private int id; private String name; ...

  5. c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出

    c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...

  6. java实现excel的导入导出(poi详解)[转]

    java实现excel的导入导出(poi详解) 博客分类: java技术 excel导出poijava  经过两天的研究,现在对excel导出有点心得了.我们使用的excel导出的jar包是poi这个 ...

  7. NodeJs之EXCEL文件导入导出MongoDB数据库数据

    NodeJs之EXCEL文件导入导出MongoDB数据库数据 一,介绍与需求 1.1,介绍 (1),node-xlsx : 基于Node.js解析excel文件数据及生成excel文件. (2),ex ...

  8. java 中Excel的导入导出

    部分转发原作者https://www.cnblogs.com/qdhxhz/p/8137282.html雨点的名字  的内容 java代码中的导入导出 首先在d盘创建一个xlsx文件,然后再进行一系列 ...

  9. PowerDesigner数据库设计PDM基于Excel的导入导出总结

    经常用到pdm来管理代码,一两张表,手写一下还凑合,一旦表多了,就慌了.于是,开始学习用vbs进行Excel的来快速导入导出操作PDM就变得很紧急了,搜罗了网络上的很多vbs脚本,各有各的优点,但对于 ...

随机推荐

  1. linux 使用sftp命令

    1.使用SecureCRT软件进入sftp界面 2.常用的一些命令 服务器                 本地                   进入目录     cd lcd 查看目录结构    ...

  2. github改local用户名和email

    github改local用户名和email 进入cd ~/.ssh 修改git config --global user.name “用户名” config --global user.email 电 ...

  3. MySql学习(五) —— 数据库优化理论篇(一)

    一.数据库管理系统 数据库管理系统(Database Management System, DBMS) 衡量是否是数据库的标准: ACID:是指在数据库管理系统(DBMS)中事务所具有的四个特性: 1 ...

  4. nmon--非常棒的LINUX/AIX性能计数器监测和分析工具

    转自51Testinghttp://bbs.51testing.com/viewthread.php?tid=116526 经常看到很多人讨论说loadrunner对linux/aix的性能监测太少, ...

  5. php foreach 语法的遍历来源数组如果不是一个有效数组php会出现错误警告 Invalid argument supplied for foreach()

    在php中,foreach语法的遍历来源数组如果不是一个有效数组,php会出现错误警告 Invalid argument supplied for foreach() ,但是很多时候这个数组是取自某些 ...

  6. C#之委托

    委托是C#中非常重要的一个概念,并在C#中得到了丰富的应用,如事件,线程等.那什么是委托呢?具体来说,委托是一种引用方法的类型.一旦为委托分配了方法,委托将与该方法具有完全相同的行为.委托方法的使用可 ...

  7. Haskell 参考资料

    1.Haskell 中文社区:www.haskellcn.org 2.Haskell   官网:     www.haskell.org 3.Haskell   函数查询:www.haskell.or ...

  8. DIV的不能包住子集解决办法

    在div的样式中加上:overflow:hidden,或者float:left或right

  9. TCP、UDP、RTP(RTCP)异同与区别

    OSI七层模型OSI 中的层            功能                                                        TCP/IP协议族 应 用层   ...

  10. android studio 换护眼的颜色步骤

    设置--->Editor-->General-->Default Text-->Background护眼色是#D2E3C7