显示“文件格式”错误,是因为你赋了错误的参数,比如你直接添加第二张工作表setSheetName(1, "name"),但并不存在第一张工作表setSheetName(0, "name")。添加数据参见这个例子:import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/**
* This example demonstrates opening a workbook, modifying it and writing
* the results back out.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class ReadWriteWorkbook
{
public static void main(String[] args)
throws IOException
{
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream("foo.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(2);
if (row == null)
row = sheet.createRow(2);
HSSFCell cell = row.getCell((short)3);
if (cell == null)
cell = row.createCell((short)3);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("a test"); // Write the output to a file
FileOutputStream fileOut = new FileOutputStream("foo.xls");
wb.write(fileOut);
fileOut.close();
}
}
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/**
* This example demonstrates opening a workbook, modifying it and writing
* the results back out.
*
* @author Glen Stampoultzis (glens at apache.org)
*/
public class ReadWriteWorkbook
{
public static void main(String[] args)
throws IOException
{
POIFSFileSystem fs =
new POIFSFileSystem(new FileInputStream("foo.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(2);
if (row == null)
row = sheet.createRow(2);
HSSFCell cell = row.getCell((short)3);
if (cell == null)
cell = row.createCell((short)3);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue("a test"); // Write the output to a file
FileOutputStream fileOut = new FileOutputStream("foo.xls");
wb.write(fileOut);
fileOut.close();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货