java中,如何动态生成HSSFCell cell0= row.createCell(..)中的cell0,cell1,cell2,cell3........

java中,如何动态生成HSSFCell cell0= row.createCell(..)中的cell0,cell1,cell2,cell3........,第1张

根据你下面的这段要求:

“就是列数有时有三个,有时有四个,这些都是不确定的,所以想动态生成cell0,不用去考虑到底生成多少个HSSFCell对象”

给个思路的代码(我是直接写的,你拿来用时要改改):

List list=//你用来动态生成的数据列表

int rno=listsize(); //行数

//列数如下,我想这是你的问题的关键

int cno=listget(0)getClass()getDeclaredFields()length;//看不懂就照用试试。

XSSFRow row=null;

XSSFCell cell = null;

for(int i=0;i<rno;i++){

row=sheetcreateRow(i);

for(int j=0;j<cno;j++){

cell = rowcreateCell(j);

//我想你在这里要取值时也是个问题。看你的list封装的是什么了

}

}

引入poi的jar包,大致如下:

读取代码如下,应该能看得明白吧

import javaioFileInputStream;

import javaioFileNotFoundException;

import javaioIOException;

import javaioInputStream;

import javamathBigDecimal;

import javatextDecimalFormat;

import javatextSimpleDateFormat;

import orgapachepoixssfusermodelXSSFCell;

import orgapachepoixssfusermodelXSSFRow;

import orgapachepoixssfusermodelXSSFSheet;

import orgapachepoixssfusermodelXSSFWorkbook;

public class ExcelUtil2007 {

/读取excel文件流的指定索引的sheet

  @param inputStream excel文件流

  @param sheetIndex 要读取的sheet的索引

  @return

  @throws FileNotFoundException

  @throws IOException

 /

public static XSSFSheet readExcel(InputStream inputStream,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(inputStream)getSheetAt(sheetIndex);

}

/读取excel文件的指定索引的sheet

  @param filePath excel文件路径

  @param sheetIndex 要读取的sheet的索引

  @return

  @throws IOException 

  @throws FileNotFoundException 

 /

public static XSSFSheet readExcel(String filePath,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(filePath)getSheetAt(sheetIndex);

}

/读取excel文件的指定索引的sheet

  @param filePath excel文件路径

  @param sheetName 要读取的sheet的名称

  @return

  @throws IOException 

  @throws FileNotFoundException 

 /

public static XSSFSheet readExcel(String filePath,String sheetName) throws FileNotFoundException, IOException

{

return readExcel(filePath)getSheet(sheetName);

}

/读取excel文件,返回XSSFWorkbook对象

  @param filePath excel文件路径

  @return 

  @throws FileNotFoundException

  @throws IOException

 /

public static XSSFWorkbook readExcel(String filePath) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(new FileInputStream(filePath));

return wb;

}

/读取excel文件流,返回XSSFWorkbook对象

  @param inputStream excel文件流

  @return

  @throws FileNotFoundException

  @throws IOException

 /

public static XSSFWorkbook readExcel(InputStream inputStream) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(inputStream);

return wb;

}

/读取excel中指定的单元格,并返回字符串形式的值

  1数字

  2字符

  3公式(返回的为公式内容,非单元格的值)

  4空

  @param st 要读取的sheet对象

  @param rowIndex 行索引

  @param colIndex 列索引

  @param isDate 是否要取的是日期(是则返回yyyy-MM-dd格式的字符串)

  @return

 /

public static String getCellString(XSSFSheet st,int rowIndex,int colIndex,boolean isDate){

String s="";

XSSFRow row=stgetRow(rowIndex);

if(row == null) return "";

XSSFCell cell=rowgetCell(colIndex);

if(cell == null) return "";

if (cellgetCellType() == 0) {//数字

if(isDate)s=new SimpleDateFormat("yyyy-MM-dd")format(cellgetDateCellValue());

else s = trimPointO(StringvalueOf(getStringValue(cell))trim());

}else if (cellgetCellType() == 1){//字符(excel中的空格,不是全角,也不是半角,不知道是神马,反正就是" "这个)

s=cellgetRichStringCellValue()getString()replaceAll(" ", " ")trim();

// s=cellgetStringCellValue();//07API新增,好像跟上一句一致

}

else if (cellgetCellType() == 2){//公式

s=cellgetCellFormula();

}

else if (cellgetCellType() == 3){//空

s="";

}

return s;

}

/如果数字以 0 结尾,则去掉0

  @param s

  @return

 /

public static String trimPointO(String s) {

if (sendsWith("0"))

return ssubstring(0, slength() - 2);

else

return s;

}

/处理科学计数法和百分比模式的数字单元格

  @param cell

  @return

 /

public static String getStringValue(XSSFCell cell) {

String sValue = null;

short dataFormat = cellgetCellStyle()getDataFormat();

double d = cellgetNumericCellValue();

BigDecimal b = new BigDecimal(DoubletoString(d));

//百分比样式的

if (dataFormat == 0xa || dataFormat == 9) {

b=bmultiply(new BigDecimal(100));

//String temp=btoPlainString();

DecimalFormat df=new DecimalFormat("000");//保留两位小数的百分比格式

sValue = dfformat(b) + "%";

}else{

sValue = btoPlainString();

}

return sValue;

}

}

XSSFWorkbook wb=new XSSFWorkbook(参数);中的参数是InputStream ,你直接XSSFWorkbook wb=new XSSFWorkbook(fs);就可以了。

第一步查询数据--这一步读者自行实现自己的数据查询 List<PointInfo> points = null;

points = thisdaogetAllCollect(userId);

final Map<String, List<PointInfo>> pointMap = new HashMap<>();

for (final PointInfo pointInfo : points) {

final String pt = pointInfogetPointType(); if (pointMapcontainsKey(pt)) {final List<PointInfo> subList = pointMapget(pt);

subListadd(pointInfo);

} else {final List<PointInfo> subList = new ArrayList<>();subListadd(pointInfo);

pointMapput(pt, subList

第二步:生成工作簿

final SXSSFWorkbook wb = new SXSSFWorkbook();

// 对每一种类型生成一个sheet

for (final MapEntry<String, List<PointInfo>> entry : pointMapentrySet()) {

final List<PointInfo> pts = entrygetValue();

// 获取每种类型的名字--作为sheet显示名称--如果不需要分sheet可忽略

String typeName = "";

if (thisdaogetTypeByTypeCode(ptsget(0)getPointType()) != null) {

typeName = thisdaogetTypeByTypeCode(ptsget(0)getPointType())getPointTypeName();

}

final Sheet sheet = wbcreateSheet(typeName);

//生成用于插入的容器--这个方法返回的类型在老api中不同

final Drawing patriarch = sheetcreateDrawingPatriarch();

// 为sheet1生成第一行,用于放表头信息

final Row row = sheetcreateRow(0);

// 第一行的第一个单元格的值

Cell cell = rowcreateCell((short) 0);

cellsetCellValue("详细地址");

cell = rowcreateCell((short) 1);

cellsetCellValue("经度");

cell = rowcreateCell((short) 2);

cellsetCellValue("纬度");

cell = rowcreateCell((short) 3);

for (int i = 0; i < ptssize(); i++) {

final Row each = sheetcreateRow(i + 1);

Cell infoCell = eachcreateCell((short) 0);

infoCellsetCellValue(ptsget(i)getAddrDetail());

infoCell = eachcreateCell((short) 1);

infoCellsetCellValue(ptsget(i)getX());

infoCell = eachcreateCell((short) 2);

infoCellsetCellValue(ptsget(i)getY());

infoCell = eachcreateCell((short) 3);

//查询获取路径信息--该步读者自定义

PointPic pic = thisdaogetPicInfoByPointId(ptsget(i)getId());

try {

if (pic != null) {

for (int k = 0; k < 6; k++) {//因为有六张,所以循环6次

final short colNum = (short) (4+k);

infoCell = eachcreateCell(colNum);

BufferedImage img = null;

switch (k) {

case 0:

if (!StringUtilsisEmpty(picgetPicOneAddr())) {

File imgFile = new File(picgetPicOneAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

case 1:

if (!StringUtilsisEmpty(picgetPicTwoAddr())) {

File imgFile = new File(picgetPicTwoAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

case 2:

if (!StringUtilsisEmpty(picgetPicThreeAddr())) {

File imgFile = new File(picgetPicThreeAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

case 3:

if (!StringUtilsisEmpty(picgetPicFourAddr())) {

File imgFile = new File(picgetPicFourAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

case 4:

if (!StringUtilsisEmpty(picgetPicFiveAddr())) {

File imgFile = new File(picgetPicFiveAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

case 5:

if (!StringUtilsisEmpty(picgetPicSixAddr())) {

File imgFile = new File(picgetPicSixAddr());

img = ImageIOread(imgFile);

imgFile = null;

}

break;

}

ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();

ImageIOwrite(img, "jpg", byteArrayOut);

img = null;

//设置每张插入位置

final XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, colNum,

i + 1, (short) (colNum + 1), i + 2);//参数为插入在表格的坐标,可以自行查看api研究参数

anchorsetAnchorType(0);

// 插入

patriarchcreatePicture(anchor, wbaddPicture(

byteArrayOuttoByteArray(), HSSFWorkbookPICTURE_TYPE_JPEG));

byteArrayOutclose();

byteArrayOut = null;

}

pic = null;

}

} catch (final Exception e) {

eprintStackTrace();

}

}

}

final ByteArrayOutputStream os = new ByteArrayOutputStream();

try {

wbwrite(os);

} catch (final IOException e) {

eprintStackTrace();

}

final byte[] content = ostoByteArray();

final String url = VarBASE_URL+ Fileseparator + "outputxls";//读者自定义路径

final File file = new File(url);// Excel文件生成后存储的位置。

OutputStream fos = null;

try {

fos = new FileOutputStream(file);

foswrite(content);

osclose();

fosclose();

} catch (final Exception e) {

eprintStackTrace();

}

return url;//文件保存成功

可以是一下GCExcel这个组件,相较POI,GCExcel在功能上更加完善,并且完全参照Excel的规范。如果想要删除行不留空白行,直接在GCExcel调用删除命令就可以了,不需要再做上移的 *** 作,更加易于理解。删除行时只需要输入行的名称或者索引,像这样:

worksheet2getRange("A3:A5")getEntireRow()delete();

或worksheet2getRange("2:4")delete(); 支持删除多行。

参考文档:网页链接

您好,<!-- 文件下载,支持中文附件名 -->

<action name="fileDownload"

class="comtestactionfiledownFileDownloadAction">

<result name="success" type="stream">

<!-- 动态文件下载的,事先并不知道未来的文件类型,那么我们可以把它的值设置成为:application/octet-stream;charset=ISO8859-1 ,注意一定要加入charset,否则某些时候会导致下载的文件出错; -->

<param name="contentType">

application/octet-stream;charset=ISO8859-1

</param>

<param name="contentDisposition">

attachment;filename="${downloadFileName}"

</param>

<!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性

对应action类中的方法 getDownloadFileName() 其中特殊的代码就是${downloadFileName},它的效果相当于运行的时候将action对象的属性的取值动态的填充在${}中间的部分,我们可以认为它等价于+action getDownloadFileName()。 -->

<param name="inputName">inputStream</param>

<param name="bufferSize">4096</param>

</result>

</action>

----------------------------------------------------------

action中

----------------------------------------------------------

private String fileName;// 初始的通过param指定的文件名属性 set get

/ 文件名 转换编码 防止中文乱码/

public String getDownloadFileName() {

String fileName=ServletActionContextgetRequest()getParameter("fileName");

String downFileName = fileName;

try {

downFileName = new String(downFileNamegetBytes(), "ISO8859-1");

} catch (Exception e) {

eprintStackTrace();

}

return downFileName;

}

//下载的流

public InputStream getInputStream() {

String name=thisgetDownloadFileName();

// String realPath=ServletActionContextgetServletContext()getRealPath("/uploadImages")+ "/"+name; 路径错误

String realPath="/uploadImages/"+name;

InputStream in=ServletActionContextgetServletContext()getResourceAsStream(realPath);

if(null==in){

Systemoutprintln("Can not find a javaioInputStream with the name [inputStream] in the invocation stack Check the <param name=\"inputName\"> tag specified for this action检查action中文件下载路径是否正确");

}

return ServletActionContextgetServletContext()getResourceAsStream(realPath);

}

@Override

public String execute() throws Exception {

return SUCCESS;

}

以上就是关于java中,如何动态生成HSSFCell cell0= row.createCell(..)中的cell0,cell1,cell2,cell3........全部的内容,包括:java中,如何动态生成HSSFCell cell0= row.createCell(..)中的cell0,cell1,cell2,cell3........、java怎么读取excel数据、JAVA编程中用Apache POI 怎么用SXSSFWorkbook对已存在的excel(.xlsx) *** 作进行写数据 *** 作等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/9646052.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-30
下一篇2023-04-30

发表评论

登录后才能评论

评论列表(0条)

    保存