不多說,直接上代碼
import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.RoundingMode; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sjdf.erp.common.constant.CommonPlatformConstant; import com.sjdf.erp.common.utils.PlatformUtils; public class ExcelUntilTest { private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUntilTest.class); public static final String XLSX = ".xlsx"; public static final String XLS=".xls"; /** * Excel導出 * @param title 導出Excel文件名稱 * @param rowList 第一個List為表頭,其余行為表數據 * @param resp HttpServletResponse 對象 * @throws IOException */ public static void writeExcel(String title,List<List<Object>> rowList,HttpServletResponse resp) throws IOException{ if (resp == null) { throw new NullPointerException("the HttpServletResponse is null"); } HSSFWorkbook book = warpSingleWorkbook(title, rowList, false); // 響應客戶端 String filename = new String(title.getBytes("UTF-8"), "ISO-8859-1"); resp.reset(); resp.setHeader("Content-disposition", "attachment; filename=" + filename +XLS); resp.setContentType("application/vnd.ms-excel;charset=UTF-8"); // 輸出Excel文件 book.write(resp.getOutputStream()); book.close(); } /** * Excel導出設置Workbook * @param title 導出Excel文件名稱 * @param rowList 第一個List為表頭,其余行為表數據 * @param downLoadPic 是否下載圖片 * @throws IOException */ public static HSSFWorkbook warpSingleWorkbook(String title,List<List<Object>> rowList, Boolean downLoadPic) throws IOException { String filename = title; if (!PlatformUtils.hasText(title)) { filename = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); } if (rowList == null || rowList.isEmpty()) { throw new NullPointerException("the row list is null"); } HSSFWorkbook book = new HSSFWorkbook(); // 創建表 HSSFSheet sheet = book.createSheet(filename); // 設置單元格默認寬度為15個字符 sheet.setDefaultColumnWidth(15); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 設置表頭樣式 HSSFCellStyle style = book.createCellStyle(); // 設置居左 style.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 檢測表頭數據(表頭不允許數據為空) List<Object> head = rowList.get(0); for (Object key : head) { if (!PlatformUtils.hasText(key.toString())) { book.close(); throw new NullPointerException("there is a blank exist head row"); } } // 寫數據 int size = rowList.get(0).size(); for (int i = 0; i < rowList.size(); i++) { List<Object> row = rowList.get(i); if (row == null || row.isEmpty()) { book.close(); throw new NullPointerException("the "+(i+1)+"th row is null"); } if (size != row.size()) { book.close(); throw new IllegalArgumentException("the cell number of "+(i+1)+"th row is different form the first"); } HSSFRow sr = sheet.createRow(i); for (int j = 0; j < row.size(); j++) { if (downLoadPic && i > 0 && j == 0) { sr.setHeight((short) (800)); drawPictureInfoExcel(book, patriarch, i, row.get(0).toString()); } else { setExcelValue(sr.createCell(j), row.get(j), style); } } } return book; } public static void main(String[] args) { FileOutputStream fileOut = null; try { String picUrl1 = "http://b-ssl.duitang.com/uploads/item/201502/17/20150217161549_C4K8L.jpeg"; String picUrl2 = "http://b-ssl.duitang.com/uploads/item/201512/10/20151210135838_Y2SvK.jpeg"; String picUrl3 = "http://img5.duitang.com/uploads/item/201407/23/20140723175802_LHCJU.jpeg"; List<List<Object>> rowList = new ArrayList<List<Object>>(); rowList.add(Arrays.asList("圖片", "名稱", "sku")); rowList.add(Arrays.asList(picUrl1, "名稱1", "sku01")); rowList.add(Arrays.asList(picUrl2, "名稱2", "sku02")); rowList.add(Arrays.asList(picUrl3, "名稱3", "sku03")); HSSFWorkbook wb = warpSingleWorkbook("test", rowList, false); fileOut = new FileOutputStream("D:/測試Excel.xls"); // 寫入excel文件 wb.write(fileOut); System.out.println("----Excle文件已生成------"); } catch (Exception e) { e.printStackTrace(); }finally{ if(fileOut != null){ try { fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static void drawPictureInfoExcel(HSSFWorkbook wb,HSSFPatriarch patriarch,int rowIndex,String pictureUrl){ //rowIndex代表當前行 try { if(PlatformUtils.hasText(pictureUrl)) { URL url = new URL(pictureUrl); //打開鏈接 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //設置請求方式為"GET" conn.setRequestMethod("GET"); //超時響應時間為5秒 conn.setConnectTimeout(5 * 1000); //通過輸入流獲取圖片數據 InputStream inStream = conn.getInputStream(); //得到圖片的二進制數據,以二進制封裝得到數據,具有通用性 byte[] data = readInputStream(inStream); //anchor主要用於設置圖片的屬性 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250,(short) 0, rowIndex, (short) 0, rowIndex); //Sets the anchor type (圖片在單元格的位置) //0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells. anchor.setAnchorType(3); patriarch.createPicture(anchor, wb.addPicture(data, HSSFWorkbook.PICTURE_TYPE_JPEG)); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //創建一個Buffer字符串 byte[] buffer = new byte[1024]; //每次讀取的字符串長度,如果為-1,代表全部讀取完畢 int len = 0; //使用一個輸入流從buffer里把數據讀取出來 while( (len=inStream.read(buffer)) != -1 ){ //用輸出流往buffer里寫入數據,中間參數代表從哪個位置開始讀,len代表讀取的長度 outStream.write(buffer, 0, len); } //關閉輸入流 inStream.close(); //把outStream里的數據寫入內存 return outStream.toByteArray(); } /** * 設置Excel浮點數可做金額等數據統計 * @param cell 單元格類 * @param value 傳入的值 */ public static void setExcelValue(HSSFCell cell, Object value, HSSFCellStyle style){ // 寫數據 if (value == null) { cell.setCellValue(""); }else { if (value instanceof Integer || value instanceof Long) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(Long.valueOf(value.toString())); } else if (value instanceof BigDecimal) { cell.setCellType(Cell.CELL_TYPE_NUMERIC); cell.setCellValue(((BigDecimal)value).setScale(CommonPlatformConstant.INT_3, RoundingMode.HALF_UP).doubleValue()); } else { cell.setCellValue(value.toString()); } cell.setCellStyle(style); } } }
// 參數解析
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 250,(short) 0, rowIndex, (short) 0, rowIndex)
Parameters:
dx1 - the x coordinate within the first cell.//定義了圖片在第一個cell內的偏移x坐標,既左上角所在cell的偏移x坐標,一般可設0
dy1 - the y coordinate within the first cell.//定義了圖片在第一個cell的偏移y坐標,既左上角所在cell的偏移y坐標,一般可設0
dx2 - the x coordinate within the second cell.//定義了圖片在第二個cell的偏移x坐標,既右下角所在cell的偏移x坐標,一般可設0
dy2 - the y coordinate within the second cell.//定義了圖片在第二個cell的偏移y坐標,既右下角所在cell的偏移y坐標,一般可設0
col1 - the column (0 based) of the first cell.//第一個cell所在列,既圖片左上角所在列
row1 - the row (0 based) of the first cell.//圖片左上角所在行
col2 - the column (0 based) of the second cell.//圖片右下角所在列
row2 - the row (0 based) of the second cell.//圖片右下角所在行
---------------------
作者:中華雪碧
來源:CSDN
原文:https://blog.csdn.net/gagewang1/article/details/53870843?utm_source=copy
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!