JAVA如何向指定的EXCEL单元格中写入数据??
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA如何向指定的EXCEL单元格中写入数据??相关的知识,希望对你有一定的参考价值。
我有一个EXCEL模板,想在模板的固定单元格中写入相应内容,我之前实现的虽然能写入数据,但是模板中原来的数据缺都没有了,帮帮忙啊,挺着急的~
我们项目里用的 供你参考,没写全,你可以自己百度下import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* 导出excel
* @param reportParams 导出excel列名标示
* @param list导出excel值
* @param headersexcel头
* @param reportName·excel的sheet名
* @param response
* @param startRow从哪一行开始放list值
* @param startCol 从哪一列开始放list值
* @return
*/
public boolean report(ReportBean rb, List list, XlsHeaderBean[] headers, String reportName, HttpServletResponse response, int startRow, int startCol, HttpServletRequest request)
WritableWorkbook wwb = null;
OutputStream os;
boolean flag = true;
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String strDate = format.format(date);
try
// 用Workbook类的工厂方法创建工作薄(Workbook)对象
response.setContentType("application/x-msdownload");
String sheetName = "report";
sheetName = sheetName.replaceAll(":", "").replaceAll("[)]", "")
.replaceAll("[(]", "");
// 这里解释一下
// attachment; 这个代表要下载的,如果去掉就编程直接打开了
// filename是文件名,另存为或者下载时,为默认的文件名
response.addHeader("Content-Disposition", "attachment; filename="
+ new String(sheetName.getBytes("UTF-8"), "ISO-8859-1")+ strDate
+ ".xls");
os = response.getOutputStream();
wwb = Workbook.createWorkbook(os);
catch (IOException e)
e.printStackTrace();
return flag = false;
if (wwb != null)
// 创建一个可写入的工作表
// Workbook的createSheet方法两个参数,1名称,2位置
WritableSheet ws = wwb.createSheet(reportName, 0);
// 下面开始添加单元格
// 导出excel
try
Label labelC = null;
for(int j = 0; j < headers.length; j++)
if(headers[j].isUnion())
ws.mergeCells(headers[j].getCol(), headers[j].getRow(), headers[j].getCol()+headers[j].getColLength(), headers[j].getRow()+headers[j].getRowLength());
labelC = new Label(headers[j].getCol(), headers[j].getRow(), headers[j].getValue());
ws.addCell(labelC);
catch (RowsExceededException e)
e.printStackTrace();
catch (WriteException e)
e.printStackTrace();
String value = null;
for (int i = 0; i < list.size(); i++)
Map values = (Map)list.get(i);
for (int j = 0; j < rb.getReportParams().length; j++)
// 这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行
Label labelC;
if(values.get(rb.getReportParams()[j]) == null)
value = "";
else
if(values.get(rb.getReportParams()[j]) instanceof java.util.Date)
value = format.format(values.get(rb.getReportParams()[j]));
else if(values.get(rb.getReportParams()[j]) instanceof java.math.BigDecimal)
value = values.get(rb.getReportParams()[j]).toString();
else
value = values.get(rb.getReportParams()[j]).toString();
labelC = new Label(j+startCol, i + startRow, value);
try
// 将生成的单元格添加到工作表中
ws.addCell(labelC);
catch (RowsExceededException e)
e.printStackTrace();
return flag = false;
catch (WriteException e)
e.printStackTrace();
return flag = false;
if(rb.isHasImg())
String rootPath = this.getServletContext().getRealPath("savefiles");
String imgPath = rb.getImgPath();
if(rootPath != null && rootPath.compareTo("") != 0 && imgPath != null && imgPath.compareTo("") !=0)
String[] strs = imgPath.split("\\/");
String imgName = strs[strs.length-1];
File file = new File(rootPath + File.separator + imgName);
if(file.exists())
WritableImage wi = new WritableImage(0, startRow + list.size() + 2,12,20, file);
ws.addImage(wi);
try
// 从内存中写入文件中
wwb.write();
wwb.close();
return flag;
catch (IOException e)
e.printStackTrace();
return flag = false;
catch (WriteException e)
e.printStackTrace();
return flag = false;
return flag;
参考技术A 建议你用PageOffice,能帮你解决这个问题,网上搜有很多它的示例代码呢。
POI向Excel的单元格中写入图片
HSSF是POI工程对Excel 97(-2007)文件操作的纯Java实现
XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作的纯Java实现
在POI中有HSSFPatriarch对象,该对象为画图的顶级管理器,它的createPicture(anchor, pictureIndex)方法就能够在Excel插入一张图片。
针对.xls文件导出图片
public class ExcelImageTest { public static void main(String[] args) { FileOutputStream fileOut = null; BufferedImage bufferImg = null; //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray try { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); bufferImg = ImageIO.read(new File("E:/测试图片.jpg")); ImageIO.write(bufferImg, "jpg", byteArrayOut); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet1 = wb.createSheet("test picture"); //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) HSSFPatriarch patriarch = sheet1.createDrawingPatriarch(); //anchor主要用于设置图片的属性 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8); //注意:这个方法在新版本的POI中参数类型改成了(AnchorType anchorType)
anchor.setAnchorType(3);
//插入图片 patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG)); 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(); } } } } }
本项目导入的POI版本是poi-3.11-20141221.jar,setAnchorType(int anchorType)
工具方法
//插入某个图片到指定索引的位置 private static void insertImage(HSSFWorkbook wb,HSSFPatriarch pa,byte[] data,int row,int column,int index){ //单元格为标,以左上为起点,向右移,范围0-1023 dx1 must be between 0 and 1023 int x1=0; //单元格为标,以左上为起点,向下移,范围0-1023 dy1 must be between 0 and 255 int y1=0; //单元格为标,以右上为起点,向右移,范围0-1023 dx1 must be between 0 and 1023 int x2=100; //单元格为标,以右下为起点,向下移,范围0-1023 dy1 must be between 0 and 255 int y2=22;
//后面四个参数表示图片左上角和右下角的坐标
//col1 图片的左上角放在第几个列cell,
// row1 图片的左上角放在第几个行cell,
// col2 图片的右下角放在第几个列cell,
// row2 图片的右下角放在第几个行cell,
HSSFClientAnchor anchor = new HSSFClientAnchor(x1,y1,x2,y2,(short)column,row,(short)column,row); anchor.setAnchorType(3); pa.createPicture(anchor , wb.addPicture(data,HSSFWorkbook.PICTURE_TYPE_JPEG)); }
针对.xlsx导出Excel图片
package com.org.apache.poi.xssf; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class StartPoiExcelWriterImg { public static void main(String[] args) { FileOutputStream fileOut = null; BufferedImage bufferImg = null; //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray try { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); bufferImg = ImageIO.read(new File("D:/测试图片.jpg")); ImageIO.write(bufferImg, "jpg", byteArrayOut); XSSFWorkbook wb = new XSSFWorkbook(); XSSFSheet sheet1 = wb.createSheet("Sheet1"); //XSSFSheet sheet1 = wb.getSheet("Sheet1"); //画图的顶级管理器,一个sheet只能获取一个(一定要注意这点) XSSFDrawing patriarch = sheet1.createDrawingPatriarch(); //anchor主要用于设置图片的属性 XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8); anchor.setAnchorType(3); //插入图片 patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG)); fileOut = new FileOutputStream("C:\\\\Users\\\\huage\\\\Desktop\\\\121231\\\\11111.xlsx"); // 写入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(); } } } } }
以上是关于JAVA如何向指定的EXCEL单元格中写入数据??的主要内容,如果未能解决你的问题,请参考以下文章