java excel文件_java操作excel文件

采用POI操作excel

API:http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html

poi包:http://pan.baidu.com/s/1hmIQU

一.读取excel内容

1.excel内容的值如果不是string,则用getNumericCellValue(),得到double类型,再做相应转换,如果为string,则用getStringCellValue()

public static String getExcel(int index,int rowNum,int colNum) {

//File file = new File("D:/BaiduYunDownload/excel/testdata.xls");

File file = new File("./POIexcel/testdata.xls");

String cellValue = null;

int rowN = rowNum-1;//将excel的行数-1

Row row = null;

Cell cell= null;

HSSFCell hf = null;

// Cell cell_b = null;

try {

FileInputStream in = new FileInputStream(file);

HSSFWorkbook wb = new HSSFWorkbook(in);

HSSFSheet sheet = wb.getSheetAt(index);//sheet页,index从0开始

//从哪行读取

// int firstRowNum = sheet.getFirstRowNum()+1;

// int lastRowNum = sheet.getLastRowNum();

row = sheet.getRow(rowN); //取得第几行

cell = row.getCell(colNum); //取得行的第3列,从0开始

if(cell!=null){

//((Object) hf).setEncoding(HSSFCell.ENCODING_UTF_16);

//判断excel内容的数值类型

switch(cell.getCellType()) {

case Cell.CELL_TYPE_STRING://String

cellValue = cell.getStringCellValue().trim();

break;

case Cell.CELL_TYPE_NUMERIC://number

if(HSSFDateUtil.isCellDateFormatted(cell)) {

Date date = cell.getDateCellValue();

if (date != null) {//date

cellValue = new SimpleDateFormat("yyyy-MM-dd").format(date);

} else {

cellValue = "";

}

}else {

cellValue = new DecimalFormat("###.###").format(cell.getNumericCellValue());

}

break;

case HSSFCell.CELL_TYPE_FORMULA:

// 导入时如果为公式生成的数据则无值

if (!cell.getStringCellValue().equals("")) {

cellValue = cell.getStringCellValue();

} else {

cellValue = cell.getNumericCellValue() + "";

}

break;

case HSSFCell.CELL_TYPE_BLANK:

break;

case HSSFCell.CELL_TYPE_ERROR:

cellValue = "";

break;

case HSSFCell.CELL_TYPE_BOOLEAN:

cellValue = (cell.getBooleanCellValue() == true ? "Y": "N");

break;

default:

cellValue = "";

/*

if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC) {

double i = cell.getNumericCellValue();

cellValue = String.valueOf(i);

}else{

cellValue = cell.getStringCellValue().trim();

if(cellValue.equals("")){

System.out.println(rowNum+"行的值为空");

}

}

*/

}

}

}catch (Exception e) {

e.printStackTrace();

}

return cellValue;

}

double转换为int:int i_yhfw= (int) Double.parseDouble(Demo.getExcel(index, 13));

二.设置excel内容

public static void setExcel(String path, int sheet, int row, intcol,String value) {try{

File file= newFile(path);

FileInputStream in= newFileInputStream(file);

HSSFWorkbook hw= newHSSFWorkbook(in);

HSSFSheet hsheet= hw.getSheetAt(sheet);//目标sheet的索引

HSSFRow hrow = hsheet.getRow(row-1);//目标行的索引

HSSFCell cell = hrow.createCell(col-1);//目标列的索引

HSSFRichTextString val = newHSSFRichTextString(value);

cell.setCellValue(val);

OutputStream out= new FileOutputStream(file);//获取文件输出流

hw.write(out);//将内容写到excel

out.close();

in.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

以上的方法的是HSFF只能操作03的excel,通过官方api介绍,使用XSFF可以操作07的excel,故优化代码如下,自动识别传入的excel是03的还是07的。

packagecom.excel;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.InputStream;importjava.text.DecimalFormat;importjava.text.SimpleDateFormat;importjava.util.Date;importorg.apache.poi.hssf.usermodel.HSSFCell;importorg.apache.poi.hssf.usermodel.HSSFDateUtil;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.Cell;importorg.apache.poi.ss.usermodel.Row;importorg.apache.poi.ss.usermodel.Sheet;importorg.apache.poi.ss.usermodel.Workbook;importorg.apache.poi.xssf.usermodel.XSSFCell;importorg.apache.poi.xssf.usermodel.XSSFSheet;importorg.apache.poi.xssf.usermodel.XSSFWorkbook;/***@authorQiaoJiafei

*@version创建时间:2015年11月12日 上午10:35:03

* 类说明*/

public classTestExcel037 {public static voidmain(String args[]) {

System.out.println(getExcel("D:/03excel.xls",1,2,2));

System.out.println(getExcel("D:/07excel.xlsx",1,2,2));

}public static String getExcel(String path,int index,int rowNum,intcolNum) {

File file= newFile(path);

String cellValue= "";

Workbook wb= null;

Sheet sheet= null;

Row row= null;

Cell cell= null;try{

FileInputStream in= newFileInputStream(file);if(path.endsWith(".xls")) {

wb= newHSSFWorkbook(in);

sheet= wb.getSheetAt(index-1);

}else if (path.endsWith(".xlsx")) {

wb= newXSSFWorkbook(in);

sheet= wb.getSheetAt(index-1);

}

row=sheet.getRow(rowNum);

cell=row.getCell(colNum);if(cell!=null){switch(cell.getCellType()) {caseCell.CELL_TYPE_STRING:

cellValue=cell.getStringCellValue().trim();break;caseCell.CELL_TYPE_NUMERIC:if(HSSFDateUtil.isCellDateFormatted(cell)) {

Date date=cell.getDateCellValue();if (date != null) {

cellValue= new SimpleDateFormat("yyyy-MM-dd").format(date);

}else{

cellValue= "";

}

}else{

cellValue= new DecimalFormat("###.###").format(cell.getNumericCellValue());

}break;caseCell.CELL_TYPE_FORMULA:if (!cell.getStringCellValue().equals("")) {

cellValue=cell.getStringCellValue();

}else{

cellValue= cell.getNumericCellValue() + "";

}break;caseCell.CELL_TYPE_BLANK:break;caseCell.CELL_TYPE_ERROR:

cellValue= "";break;caseHSSFCell.CELL_TYPE_BOOLEAN:

cellValue= (cell.getBooleanCellValue() == true ? "Y": "N");break;default:

cellValue= "";

}

}

in.close();

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}returncellValue;

}

}

所用jar包:

bf32150f61d4bd63c6ea635cbf838a97.png

关于DecimalFormat的用法,参考http://www.cnblogs.com/lsun/archive/2011/06/22/2087116.html

DecimalFormat 是 NumberFormat 的一个具体子类,用于格式化十进制数字。

DecimalFormat 包含一个模式 和一组符号

符号含义:

0 一个数字

# 一个数字,不包括 0

. 小数的分隔符的占位符

, 分组分隔符的占位符

; 分隔格式。

- 缺省负数前缀。

% 乘以 100 和作为百分比显示

? 乘以 1000 和作为千进制货币符显示;用货币符号代替;如果双写,用

国际货币符号代替。如果出现在一个模式中,用货币十进制分隔符代

替十进制分隔符。

X 前缀或后缀中使用的任何其它字符,用来引用前缀或后缀中的特殊字符。

例子:

DecimalFormat df1 = new DecimalFormat("0.0");

DecimalFormat df2 = new DecimalFormat("#.#");

DecimalFormat df3 = new DecimalFormat("000.000");

DecimalFormat df4 = new DecimalFormat("###.###");

System.out.println(df1.format(12.34));

System.out.println(df2.format(12.34));

System.out.println(df3.format(12.34));

System.out.println(df4.format(12.34));

结果:

12.3

12.3

012.340

12.34

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Apache POI来实现Java合并Excel文档的操作。下面是一个简单的示例代码: ```java import org.apache.poi.ss.usermodel.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ExcelMerger { public static void main(String[] args) throws IOException { String[] fileNames = {"file1.xlsx", "file2.xlsx", "file3.xlsx"}; // 需要合并的Excel文件名 Workbook mergedWorkbook = new XSSFWorkbook(); // 创建一个新的Workbook,用于存放合并后的数据 for (String fileName : fileNames) { FileInputStream inputStream = new FileInputStream(new File(fileName)); // 读取Excel文件 Workbook workbook = new XSSFWorkbook(inputStream); for (int i = 0; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); Sheet mergedSheet = mergedWorkbook.createSheet(sheet.getSheetName()); // 在新的Workbook中创建Sheet for (int j = 0; j <= sheet.getLastRowNum(); j++) { Row row = sheet.getRow(j); Row mergedRow = mergedSheet.createRow(j); // 在新的Sheet中创建Row for (int k = 0; k < row.getLastCellNum(); k++) { Cell cell = row.getCell(k); Cell mergedCell = mergedRow.createCell(k); // 在新的Row中创建Cell if (cell != null) { switch (cell.getCellType()) { case STRING: mergedCell.setCellValue(cell.getStringCellValue()); break; case NUMERIC: mergedCell.setCellValue(cell.getNumericCellValue()); break; case BOOLEAN: mergedCell.setCellValue(cell.getBooleanCellValue()); break; case FORMULA: mergedCell.setCellFormula(cell.getCellFormula()); break; default: mergedCell.setCellValue(""); break; } } else { mergedCell.setCellValue(""); } } } } inputStream.close(); } FileOutputStream outputStream = new FileOutputStream("merged.xlsx"); // 将合并后的数据写入到文件中 mergedWorkbook.write(outputStream); outputStream.close(); } } ``` 以上代码会将指定的Excel文件合并成一个新的Excel文件,并以merged.xlsx命名。需要注意的是,合并后的Excel文件中可能会存在重复的Sheet,需要根据自己的需求进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值