Excel的导入和导出功能

工作中经常会用到excel的导入和导出功能,这里我提供导入和导出类。

导入类(需要注意的地方我注释里面写好了):


  
  
  1. package cn.teacheredu.utils;
  2. import java.io.InputStream;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Date;
  7. import java.util.List;
  8. import java.util.regex.Matcher;
  9. import java.util.regex.Pattern;
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  11. import org.apache.poi.ss.usermodel.Cell;
  12. import org.apache.poi.ss.usermodel.DateUtil;
  13. import org.apache.poi.ss.usermodel.Row;
  14. import org.apache.poi.ss.usermodel.Sheet;
  15. import org.apache.poi.ss.usermodel.Workbook;
  16. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  17. /**
  18. * 被解析的Excel最好是什么样的呢?
  19. * 单元格最好都是文本格式,保存数据前自己去转换,不用poi带的转换。
  20. * 第一列 和最后一列 必须是必填字段!!!这样的你用我这个Util,得到的List就很准确了,不会出现多余的行或列。
  21. * @author TMACJ
  22. * @version 0.000000.002899
  23. */
  24. public class ImportExcelUtil {
  25. private final static String excel2003L = ".xls"; //2003- 版本的excel
  26. private final static String excel2007U = ".xlsx"; //2007+ 版本的excel
  27. static SimpleDateFormat sFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  28. static short[] yyyyMMdd = { 14, 31, 57, 58, 179, 184, 185, 186, 187, 188};
  29. static short[] HHmmss = { 20, 32, 190, 191, 192};
  30. static List< short[]> yyyyMMddList = Arrays.asList(yyyyMMdd);
  31. static List< short[]> hhMMssList = Arrays.asList(HHmmss);
  32. /**
  33. * 描述:获取IO流中的数据,组装成List<List<Object>>对象
  34. * @param in,fileName
  35. * @return
  36. * @throws IOException
  37. */
  38. public List<List<String>> getBankListByExcel(InputStream in,String fileName) throws Exception{
  39. List<List<String>> list = null;
  40. //创建Excel工作薄
  41. Workbook work = this.getWorkbook(in,fileName);
  42. if( null == work){
  43. throw new Exception( "创建Excel工作薄为空!");
  44. }
  45. Sheet sheet = null;
  46. Row row = null;
  47. Cell cell = null;
  48. list = new ArrayList<List<String>>();
  49. //遍历Excel中所有的sheet
  50. for ( int i = 0; i < work.getNumberOfSheets(); i++) {
  51. sheet = work.getSheetAt(i);
  52. if(sheet== null){ continue;}
  53. int totalCell = sheet.getRow( 0).getPhysicalNumberOfCells(); //标题行一共有多少列
  54. //遍历当前sheet中的所有行
  55. for ( int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+ 1; j++) {
  56. row = sheet.getRow(j);
  57. if(row== null || validateRow(row) || row.getPhysicalNumberOfCells() < totalCell){ continue;} //3个条件,有一个为true就不会往list里加,不仅过滤空行还过滤了列数不够的行,这点要注意,要求表中前后的列都是必填的。
  58. //遍历所有的列
  59. List<String> li = new ArrayList<String>();
  60. for ( int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
  61. cell = row.getCell(y);
  62. li.add( this.getCellData(cell));
  63. }
  64. list.add(li);
  65. }
  66. // 简单起见,这里只解析第一个工作簿!
  67. break;
  68. }
  69. work.close();
  70. return list;
  71. }
  72. // 过滤空行,(其中一行的数据的确都为空,可是其原本的格式还在,并没有连带删除,这样计算出来的行数就不真实,比真实的大)
  73. private boolean validateRow(Row row) throws Exception{
  74. // for (Cell cell : row) {
  75. //
  76. // }
  77. //只判断第一列。第一列为空就代表这行的数据无效
  78. if (row.getCell( 0).getCellType() == Cell.CELL_TYPE_BLANK || "".equals( this.getCellData(row.getCell( 0)))) {
  79. return true;
  80. }
  81. return false; //不是空行
  82. }
  83. /**
  84. * 描述:根据文件后缀,自适应上传文件的版本
  85. * @param inStr,fileName
  86. * @return
  87. * @throws Exception
  88. */
  89. public Workbook getWorkbook(InputStream inStr,String fileType) throws Exception{
  90. Workbook wb = null;
  91. if(excel2003L.equals(fileType)){
  92. wb = new HSSFWorkbook(inStr); //2003-
  93. } else if(excel2007U.equals(fileType)){
  94. wb = new XSSFWorkbook(inStr); //2007+
  95. } else{
  96. throw new Exception( "解析的文件格式有误!");
  97. }
  98. return wb;
  99. }
  100. /**
  101. * 获取单元中值(字符串类型)
  102. *
  103. * @param cell
  104. * @return
  105. * @throws Exception
  106. */
  107. public String getCellData(Cell cell) throws Exception {
  108. String cellValue = "";
  109. if (cell != null) {
  110. try {
  111. switch (cell.getCellType()) {
  112. case Cell.CELL_TYPE_BLANK: //空白
  113. cellValue = "";
  114. break;
  115. case Cell.CELL_TYPE_NUMERIC: //数值型 0----日期类型也是数值型的一种
  116. if (DateUtil.isCellDateFormatted(cell)) {
  117. short format = cell.getCellStyle().getDataFormat();
  118. if (yyyyMMddList.contains(format)) {
  119. sFormat = new SimpleDateFormat( "yyyy-MM-dd");
  120. } else if (hhMMssList.contains(format)) {
  121. sFormat = new SimpleDateFormat( "HH:mm:ss");
  122. }
  123. Date date = cell.getDateCellValue();
  124. cellValue = sFormat.format(date);
  125. } else {
  126. cell.setCellType(Cell.CELL_TYPE_STRING);
  127. cellValue = replaceBlank(cell.getStringCellValue());
  128. //Double numberDate = new BigDecimal(cell.getNumericCellValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//似乎还是有点问题
  129. //cellValue = numberDate + "";
  130. }
  131. break;
  132. case Cell.CELL_TYPE_STRING: //字符串型 1
  133. cellValue = replaceBlank(cell.getStringCellValue());
  134. break;
  135. case Cell.CELL_TYPE_FORMULA: //公式型 2
  136. cell.setCellType(Cell.CELL_TYPE_STRING);
  137. cellValue = replaceBlank(cell.getStringCellValue());
  138. break;
  139. case Cell.CELL_TYPE_BOOLEAN: //布尔型 4
  140. cellValue = String.valueOf(cell.getBooleanCellValue());
  141. break;
  142. case Cell.CELL_TYPE_ERROR: //错误 5
  143. cellValue = "!#REF!";
  144. break;
  145. }
  146. } catch (Exception e) {
  147. throw new Exception( "读取Excel单元格数据出错:" + e.getMessage());
  148. }
  149. }
  150. return cellValue;
  151. }
  152. public static String replaceBlank(String source) {
  153. String dest = "";
  154. if (source != null) {
  155. Pattern p = Pattern.compile( "\t|\r|\n");
  156. Matcher m = p.matcher(source);
  157. dest = m.replaceAll( "");
  158. }
  159. return dest.trim();
  160. }
  161. }

导出类(.XLS格式):


  
  
  1. package cn.teacheredu.utils;
  2. import java.io.OutputStream;
  3. import java.net.URLEncoder;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.List;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.apache.commons.lang3.time.DateFormatUtils;
  11. import org.apache.poi.hssf.usermodel.HSSFCell;
  12. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  13. import org.apache.poi.hssf.usermodel.HSSFFont;
  14. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  15. import org.apache.poi.hssf.usermodel.HSSFRow;
  16. import org.apache.poi.hssf.usermodel.HSSFSheet;
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  18. import org.apache.poi.hssf.util.HSSFColor;
  19. import org.apache.poi.ss.util.CellRangeAddress;
  20. /**
  21. * 通用的导出Excel类,如果需要自定义格式的,参照此类自己再写类或方法来实现
  22. * dataList里的每一个Object数组一个元素(object[0])都是序号,不可放真实数据
  23. * @author TMACJ
  24. */
  25. public class ExportExcelUtil {
  26. private String title; // 导出表格的表名
  27. private String[] rowName; // 导出表格的列名
  28. private List<Object[]> dataList = new ArrayList<Object[]>(); // 对象数组的List集合
  29. private HttpServletResponse response;
  30. private HttpServletRequest request;
  31. /**
  32. * 实例化导出类
  33. * @param title 导出表格的表名,最好是英文,中文可能出现乱码
  34. * @param rowName 导出表格的列名数组
  35. * @param dataList 对象数组的List集合
  36. * @param response
  37. */
  38. public ExportExcelUtil(String title,String[] rowName,List<Object[]> dataList, HttpServletRequest request, HttpServletResponse response){
  39. this.title=title;
  40. this.rowName=rowName;
  41. this.dataList=dataList;
  42. this.response = response;
  43. this.request = request;
  44. }
  45. // 导出数据
  46. public void exportData() throws Exception{
  47. HSSFWorkbook workbook = new HSSFWorkbook(); // 创建一个excel对象
  48. HSSFSheet sheet =workbook.createSheet(title); // 创建表格
  49. //sheet.setDefaultRowHeightInPoints(18.5f);
  50. // sheet样式定义
  51. HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook, 16); // 头样式
  52. HSSFCellStyle columnStyle = this.getColumnStyle(workbook, 14); // 标题样式
  53. HSSFCellStyle style = this.getStyle(workbook, 11); // 单元格样式
  54. sheet.addMergedRegion( new CellRangeAddress( 0, 0, 0, (rowName.length- 1))); // 合并第一行的所有列
  55. // 产生表格标题行
  56. HSSFRow rowm =sheet.createRow( 0); // 行
  57. rowm.setHeightInPoints( 26f);
  58. HSSFCell cellTiltle =rowm.createCell( 0); // 单元格
  59. cellTiltle.setCellStyle(columnTopStyle);
  60. cellTiltle.setCellValue(title);
  61. int columnNum = rowName.length; // 表格列的长度
  62. HSSFRow rowRowName = sheet.createRow( 1); // 在第二行创建行
  63. HSSFCellStyle cells =workbook.createCellStyle();
  64. cells.setBottomBorderColor(HSSFColor.BLACK.index);
  65. rowRowName.setRowStyle(cells);
  66. // 循环 将列名放进去
  67. for ( int i = 0; i < columnNum; i++) {
  68. HSSFCell cellRowName = rowRowName.createCell(i);
  69. cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 单元格类型
  70. HSSFRichTextString text = new HSSFRichTextString(rowName[i]); // 得到列的值
  71. cellRowName.setCellValue(text); // 设置列的值
  72. cellRowName.setCellStyle(columnStyle); // 样式
  73. }
  74. // 将查询到的数据设置到对应的单元格中
  75. for ( int i = 0; i < dataList.size(); i++) {
  76. Object[] obj = dataList.get(i); //遍历每个对象
  77. HSSFRow row = sheet.createRow(i+ 2); //创建所需的行数
  78. for ( int j = 0; j < obj.length; j++) {
  79. HSSFCell cell = null; //设置单元格的数据类型
  80. if(j== 0){
  81. // 第一列设置为序号
  82. cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
  83. cell.setCellValue(i+ 1);
  84. } else{
  85. cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
  86. if(! "".equals(obj[j]) && obj[j] != null){
  87. cell.setCellValue(obj[j].toString()); //设置单元格的值
  88. } else{
  89. cell.setCellValue( " ");
  90. }
  91. }
  92. cell.setCellStyle(style); // 样式
  93. }
  94. }
  95. // 让列宽随着导出的列长自动适应,但是对中文支持不是很好 也可能在linux(无图形环境的操作系统)下报错,报错再说
  96. for ( int i = 0; i < columnNum; i++) {
  97. sheet.autoSizeColumn(i);
  98. sheet.setColumnWidth(i, sheet.getColumnWidth(i)+ 888); //适当再宽点
  99. }
  100. if(workbook != null){
  101. // 输出到服务器上
  102. // FileOutputStream fileOutputStream = new FileOutputStream("D:/user.xls");
  103. // workbook.write(fileOutputStream);//将数据写出去
  104. // fileOutputStream.close();//关闭输出流
  105. // 输出到用户浏览器上
  106. OutputStream out = response.getOutputStream();
  107. try {
  108. // excel 表文件名
  109. String fileName = title + DateFormatUtils.format( new Date(), "yyyyMMddHHmmss") + ".xls";
  110. String fileName11 = "";
  111. String userAgent = request.getHeader( "USER-AGENT");
  112. if(StringUtils.contains(userAgent, "Firefox") || StringUtils.contains(userAgent, "firefox")){ //火狐浏览器
  113. fileName11 = new String(fileName.getBytes(), "ISO8859-1");
  114. } else{
  115. fileName11 = URLEncoder.encode(fileName, "UTF-8"); //其他浏览器
  116. }
  117. String headStr = "attachment; filename=\"" + fileName11 + "\"";
  118. response.setContentType( "APPLICATION/OCTET-STREAM");
  119. response.setCharacterEncoding( "UTF-8");
  120. response.setHeader( "Content-Disposition", headStr);
  121. workbook.write(out);
  122. out.flush();
  123. workbook.close();
  124. } catch (Exception e) {
  125. throw e;
  126. } finally {
  127. if ( null != out) {
  128. out.close();
  129. }
  130. }
  131. }
  132. }
  133. public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook,int fontSize) {
  134. // 设置字体
  135. HSSFFont font = workbook.createFont();
  136. //设置字体大小
  137. font.setFontHeightInPoints(( short)fontSize);
  138. //字体加粗
  139. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  140. //设置字体名字
  141. font.setFontName( "宋体");
  142. //设置样式;
  143. HSSFCellStyle style = workbook.createCellStyle();
  144. //在样式用应用设置的字体;
  145. style.setFont(font);
  146. //设置自动换行;
  147. style.setWrapText( false);
  148. //设置水平对齐的样式为居中对齐;
  149. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  150. //设置垂直对齐的样式为居中对齐;
  151. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  152. return style;
  153. }
  154. public HSSFCellStyle getColumnStyle(HSSFWorkbook workbook,int fontSize) {
  155. // 设置字体
  156. HSSFFont font = workbook.createFont();
  157. //设置字体大小
  158. font.setFontHeightInPoints(( short)fontSize);
  159. //字体加粗
  160. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  161. //设置字体名字
  162. font.setFontName( "宋体");
  163. //设置样式;
  164. HSSFCellStyle style = workbook.createCellStyle();
  165. //设置底边框;
  166. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  167. //设置底边框颜色;
  168. style.setBottomBorderColor(HSSFColor.BLACK.index);
  169. //设置左边框;
  170. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  171. //设置左边框颜色;
  172. style.setLeftBorderColor(HSSFColor.BLACK.index);
  173. //设置右边框;
  174. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  175. //设置右边框颜色;
  176. style.setRightBorderColor(HSSFColor.BLACK.index);
  177. //设置顶边框;
  178. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  179. //设置顶边框颜色;
  180. style.setTopBorderColor(HSSFColor.BLACK.index);
  181. //在样式用应用设置的字体;
  182. style.setFont(font);
  183. //设置自动换行;
  184. style.setWrapText( false);
  185. //设置水平对齐的样式为居中对齐;
  186. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  187. //设置垂直对齐的样式为居中对齐;
  188. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  189. return style;
  190. }
  191. public HSSFCellStyle getStyle(HSSFWorkbook workbook,int fontSize) {
  192. //设置字体
  193. HSSFFont font = workbook.createFont();
  194. //设置字体大小
  195. font.setFontHeightInPoints(( short)fontSize);
  196. //字体加粗
  197. //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  198. //设置字体名字
  199. font.setFontName( "宋体");
  200. //设置样式;
  201. HSSFCellStyle style = workbook.createCellStyle();
  202. //设置底边框;
  203. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  204. //设置底边框颜色;
  205. style.setBottomBorderColor(HSSFColor.BLACK.index);
  206. //设置左边框;
  207. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  208. //设置左边框颜色;
  209. style.setLeftBorderColor(HSSFColor.BLACK.index);
  210. //设置右边框;
  211. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  212. //设置右边框颜色;
  213. style.setRightBorderColor(HSSFColor.BLACK.index);
  214. //设置顶边框;
  215. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  216. //设置顶边框颜色;
  217. style.setTopBorderColor(HSSFColor.BLACK.index);
  218. //在样式用应用设置的字体;
  219. style.setFont(font);
  220. //设置自动换行;
  221. style.setWrapText( false);
  222. //设置水平对齐的样式为居中对齐;
  223. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  224. //设置垂直对齐的样式为居中对齐;
  225. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  226. return style;
  227. }
  228. }


导出类(.xlsx格式):


  
  
  1. package cn.teacheredu.utils;
  2. import java.io.OutputStream;
  3. import java.net.URLEncoder;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.List;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.apache.commons.lang3.time.DateFormatUtils;
  11. import org.apache.poi.hssf.util.HSSFColor;
  12. import org.apache.poi.ss.usermodel.CellStyle;
  13. import org.apache.poi.ss.usermodel.Font;
  14. import org.apache.poi.ss.util.CellRangeAddress;
  15. import org.apache.poi.xssf.streaming.SXSSFCell;
  16. import org.apache.poi.xssf.streaming.SXSSFRow;
  17. import org.apache.poi.xssf.streaming.SXSSFSheet;
  18. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  19. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  20. /**
  21. * 通用的导出Excel类,(Excel 2007 OOXML (.xlsx)格式 )如果需要自定义格式的,参照此类自己再写类或方法来实现
  22. * dataList里的每一个Object数组一个元素(object[0])都是序号,不可放真实数据
  23. * @author Zhaojie
  24. */
  25. public class ExportExcelUtil2 {
  26. private String title; // 导出表格的表名
  27. private String[] rowName; // 导出表格的列名
  28. private List<Object[]> dataList = new ArrayList<Object[]>(); // 对象数组的List集合
  29. private HttpServletResponse response;
  30. private HttpServletRequest request;
  31. /**
  32. * 实例化导出类
  33. * @param title 导出表格的表名,最好是英文,中文可能出现乱码
  34. * @param rowName 导出表格的列名数组
  35. * @param dataList 对象数组的List集合
  36. * @param response
  37. */
  38. public ExportExcelUtil2(String title,String[] rowName,List<Object[]> dataList, HttpServletRequest request, HttpServletResponse response){
  39. this.title=title;
  40. this.rowName=rowName;
  41. this.dataList=dataList;
  42. this.response = response;
  43. this.request = request;
  44. }
  45. // 导出数据
  46. public void exportData() throws Exception{
  47. SXSSFWorkbook workbook = new SXSSFWorkbook(); //声明一个工作薄 Excel 2007 OOXML (.xlsx)格式
  48. SXSSFSheet sheet = workbook.createSheet(title); // 创建表格
  49. for( int i = 1;i<rowName.length;i++){ //根据列名设置每一列的宽度
  50. int length = rowName[i].toString().length();
  51. sheet.setColumnWidth(i, 2*(length+ 1)* 256);
  52. }
  53. //sheet.setDefaultRowHeightInPoints(18.5f);
  54. // sheet样式定义
  55. CellStyle columnTopStyle = this.getColumnTopStyle(workbook, 14); // 头样式
  56. CellStyle columnStyle = this.getColumnStyle(workbook, 12); // 标题样式
  57. CellStyle style = this.getStyle(workbook, 11); // 单元格样式
  58. // 产生表格标题行
  59. sheet.addMergedRegion( new CellRangeAddress( 0, 0, 0, (rowName.length- 1))); // 合并第一行的所有列
  60. SXSSFRow rowm = sheet.createRow( 0); // 行
  61. rowm.setHeightInPoints( 31f);
  62. SXSSFCell cellTiltle = rowm.createCell( 0); // 单元格
  63. cellTiltle.setCellStyle(columnTopStyle);
  64. cellTiltle.setCellValue(title);
  65. // 产生第二行(列名)
  66. int columnNum = rowName.length; // 表格列的长度
  67. SXSSFRow rowRowName = sheet.createRow( 1); // 在第二行创建行
  68. rowRowName.setHeightInPoints( 21f);
  69. CellStyle cells = workbook.createCellStyle();
  70. cells.setBottomBorderColor(HSSFColor.BLACK.index);
  71. rowRowName.setRowStyle(cells);
  72. for ( int i = 0; i < columnNum; i++) {
  73. SXSSFCell cellRowName = rowRowName.createCell(i);
  74. cellRowName.setCellType(SXSSFCell.CELL_TYPE_STRING); // 单元格类型
  75. XSSFRichTextString text = new XSSFRichTextString(rowName[i]); // 得到列的值
  76. cellRowName.setCellValue(text); // 设置列的值
  77. cellRowName.setCellStyle(columnStyle); // 样式
  78. }
  79. // 产生其它行(将数据列表设置到对应的单元格中)注意:默认添加了第一列的序号,如果不要可以注释掉
  80. for ( int i = 0; i < dataList.size(); i++) {
  81. Object[] obj = dataList.get(i); //遍历每个对象
  82. SXSSFRow row = sheet.createRow(i+ 2); //创建所需的行数
  83. row.setHeightInPoints( 17.25f);
  84. for ( int j = 0; j < obj.length; j++) {
  85. SXSSFCell cell = null; //设置单元格的数据类型
  86. if(j== 0){
  87. // 第一列设置为序号
  88. cell = row.createCell(j,SXSSFCell.CELL_TYPE_NUMERIC);
  89. cell.setCellValue(i+ 1);
  90. } else{
  91. cell = row.createCell(j,SXSSFCell.CELL_TYPE_STRING);
  92. if(! "".equals(obj[j]) && obj[j] != null){
  93. cell.setCellValue(obj[j].toString()); //设置单元格的值
  94. } else{
  95. cell.setCellValue( " ");
  96. }
  97. }
  98. cell.setCellStyle(style); // 样式
  99. }
  100. }
  101. // 让列宽随着导出的列长自动适应,但是对中文支持不是很好 也可能在linux(无图形环境的操作系统)下报错,报错再说
  102. // for (int i = 0; i < columnNum; i++) {
  103. // sheet.autoSizeColumn(i);
  104. // sheet.setColumnWidth(i, sheet.getColumnWidth(i)+888);//适当再宽点
  105. // }
  106. if(workbook != null){
  107. // 输出到服务器上
  108. // FileOutputStream fileOutputStream = new FileOutputStream("D:/user.xls");
  109. // workbook.write(fileOutputStream);//将数据写出去
  110. // fileOutputStream.close();//关闭输出流
  111. // 输出到用户浏览器上
  112. OutputStream out = response.getOutputStream();
  113. try {
  114. // excel 表文件名
  115. String fileName = title + DateFormatUtils.format( new Date(), "yyyyMMddHHmmss") + ".xlsx";
  116. String fileName11 = "";
  117. String userAgent = request.getHeader( "USER-AGENT");
  118. if(StringUtils.contains(userAgent, "Firefox") || StringUtils.contains(userAgent, "firefox")){ //火狐浏览器
  119. fileName11 = new String(fileName.getBytes(), "ISO8859-1");
  120. } else{
  121. fileName11 = URLEncoder.encode(fileName, "UTF-8"); //其他浏览器
  122. }
  123. String headStr = "attachment; filename=\"" + fileName11 + "\"";
  124. response.setContentType( "APPLICATION/OCTET-STREAM");
  125. response.setCharacterEncoding( "UTF-8");
  126. response.setHeader( "Content-Disposition", headStr);
  127. workbook.write(out);
  128. out.flush();
  129. workbook.close();
  130. workbook.dispose();
  131. } catch (Exception e) {
  132. throw e;
  133. } finally {
  134. if ( null != out) {
  135. out.close();
  136. }
  137. }
  138. }
  139. }
  140. public CellStyle getColumnTopStyle(SXSSFWorkbook workbook,int fontSize) {
  141. // 设置字体
  142. Font font = workbook.createFont();
  143. //设置字体大小
  144. font.setFontHeightInPoints(( short)fontSize);
  145. //字体加粗
  146. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  147. //设置字体名字
  148. font.setFontName( "宋体");
  149. //设置样式;
  150. CellStyle style = workbook.createCellStyle();
  151. //在样式用应用设置的字体;
  152. style.setFont(font);
  153. //设置自动换行;
  154. style.setWrapText( false);
  155. //设置水平对齐的样式为居中对齐;
  156. style.setAlignment(CellStyle.ALIGN_CENTER);
  157. //设置垂直对齐的样式为居中对齐;
  158. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  159. return style;
  160. }
  161. public CellStyle getColumnStyle(SXSSFWorkbook workbook,int fontSize) {
  162. // 设置字体
  163. Font font = workbook.createFont();
  164. //设置字体大小
  165. font.setFontHeightInPoints(( short)fontSize);
  166. //字体加粗
  167. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  168. //设置字体名字
  169. font.setFontName( "宋体");
  170. //设置样式;
  171. CellStyle style = workbook.createCellStyle();
  172. //设置底边框;
  173. style.setBorderBottom(CellStyle.BORDER_THIN);
  174. //设置底边框颜色;
  175. style.setBottomBorderColor(HSSFColor.BLACK.index);
  176. //设置左边框;
  177. style.setBorderLeft(CellStyle.BORDER_THIN);
  178. //设置左边框颜色;
  179. style.setLeftBorderColor(HSSFColor.BLACK.index);
  180. //设置右边框;
  181. style.setBorderRight(CellStyle.BORDER_THIN);
  182. //设置右边框颜色;
  183. style.setRightBorderColor(HSSFColor.BLACK.index);
  184. //设置顶边框;
  185. style.setBorderTop(CellStyle.BORDER_THIN);
  186. //设置顶边框颜色;
  187. style.setTopBorderColor(HSSFColor.BLACK.index);
  188. //在样式用应用设置的字体;
  189. style.setFont(font);
  190. //设置自动换行;
  191. style.setWrapText( false);
  192. //设置水平对齐的样式为居中对齐;
  193. style.setAlignment(CellStyle.ALIGN_CENTER);
  194. //设置垂直对齐的样式为居中对齐;
  195. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  196. //设置背景填充色(前景色)
  197. style.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index); //设置别的颜色请去网上查询相关文档
  198. style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  199. return style;
  200. }
  201. public CellStyle getStyle(SXSSFWorkbook workbook,int fontSize) {
  202. //设置字体
  203. Font font = workbook.createFont();
  204. //设置字体大小
  205. font.setFontHeightInPoints(( short)fontSize);
  206. //字体加粗
  207. //font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  208. //设置字体名字
  209. font.setFontName( "宋体");
  210. //设置样式;
  211. CellStyle style = workbook.createCellStyle();
  212. //设置底边框;
  213. style.setBorderBottom(CellStyle.BORDER_THIN);
  214. //设置底边框颜色;
  215. style.setBottomBorderColor(HSSFColor.BLACK.index);
  216. //设置左边框;
  217. style.setBorderLeft(CellStyle.BORDER_THIN);
  218. //设置左边框颜色;
  219. style.setLeftBorderColor(HSSFColor.BLACK.index);
  220. //设置右边框;
  221. style.setBorderRight(CellStyle.BORDER_THIN);
  222. //设置右边框颜色;
  223. style.setRightBorderColor(HSSFColor.BLACK.index);
  224. //设置顶边框;
  225. style.setBorderTop(CellStyle.BORDER_THIN);
  226. //设置顶边框颜色;
  227. style.setTopBorderColor(HSSFColor.BLACK.index);
  228. //在样式用应用设置的字体;
  229. style.setFont(font);
  230. //设置自动换行;
  231. style.setWrapText( false);
  232. //设置水平对齐的样式为居中对齐;
  233. style.setAlignment(CellStyle.ALIGN_CENTER);
  234. //设置垂直对齐的样式为居中对齐;
  235. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  236. return style;
  237. }
  238. }


以上就是两个工具类~

猜你喜欢

转载自blog.csdn.net/qq_42239765/article/details/82848143
今日推荐