java聚合excel_java操作excel
1、工具準備
(1)下載poi.jar
(2)eclipse
2、Excel準備
3、代碼示例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//操作Excel工具類
public class ExcelUtils {
public static HSSFSheet ExcelSheet;
public static HSSFWorkbookExcelBook;
public static HSSFRow Row;
public static HSSFCellCell;
/**
* 加載Excel
* @param Path
* 文件路徑
*/
public static void setExcelFile(String Path) {
FileInputStream ExcelFile;
try {
ExcelFile = new FileInputStream(Path);
ExcelBook=new HSSFWorkbook(ExcelFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 值得寫入
* @param Result
* @param RowNum
* @param ColNum
* @param Path
* @param SheetName
*/
public static void setCellData(String Result, int RowNum, int ColNum,String Path,String SheetName) {
try {
ExcelSheet=ExcelBook.getSheet(SheetName);
Row = ExcelSheet.getRow(RowNum);
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取Excel中對應單元格的值
* @param RowNum
* @param CloNum
* @param SheetName
* @return
*/
public static String getCellDate(int RowNum,int CloNum,String SheetName){
ExcelSheet=ExcelBook.getSheet(SheetName);
Cell=ExcelSheet.getRow(RowNum).getCell(CloNum);
String cellData=Cell.getStringCellValue();
return cellData;
}
/**
* 獲取到sheet頁最后一行
* @param SheetName
* @return
*/
public static int getLastRowNums(String SheetName) {
try {
ExcelSheet=ExcelBook.getSheet(SheetName);
int rowCount = ExcelSheet.getLastRowNum();
return rowCount;
}catch (Exception e){
throw(e);
}
}
}
總結
以上是生活随笔為你收集整理的java聚合excel_java操作excel的全部內容,希望文章能夠幫你解決所遇到的問題。