❶ java poi導出excel要雙擊才顯示換行
在開始選項卡下面有個玩意叫自動換行,點一下就好了。
❷ 如何使用poi進行excel單元格的查找和替換
參考spire.xls for java 的查找替換方法:
import com.spire.xls.CellRange;
mport com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReplaceData {
public static void main(String[] args){
//創建Workbook實例
Workbook workbook = new Workbook();
//載入Excel文檔
workbook.loadFromFile("Test.xlsx");
//獲取第一個工作表
Worksheet worksheet = workbook.getWorksheets().get(0);
//查找工作表中的指定文字
CellRange[] ranges = worksheet.findAllString("合計", true, true);
for (CellRange range : ranges)
{
//替換為新文字
range.setText("替換");
}
//保存結果文檔
workbook.saveToFile("ReplaceData.xlsx", ExcelVersion.Version2013);
}
}
參考自官網教程
❸ java使用poi解析或處理excel的時候,如何防止數字變成科學計數法的
思路為:為了防止數字變成科學計數法方式表示,在源文件以及java代碼中都用文本的方式去生成和解析excel,具體如下:
1.生成Excel時,設置單元格格式為STRING,即:
//關鍵代碼
HSSFCellcell=newHSSFCell();
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
2.同理,解析的時候,首先要保證源excel文件中該單元格格式是文本類型的,然後在java代碼里用STRING類型去解析:
//關鍵代碼
Stringvalue=cell.getStringCellValue();
❹ 如何用java poi操作excel
註解類(將實體類加上該註解)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField
{
//導出欄位在excel中的名字
String title();
}
操作類(調用方法進行導出)
@Slf4j
public class ExcelUtil {
private static final int EXCEL_NUM_LIMIT = 200000;
/**
* 通用導出方法
*/
public static <T> void writeExcel(HttpServletResponse response, String fileName, List<T> list, Class<T> cls) {
// 1.創建一個workbook,對應一個Excel文件
SXSSFWorkbook workBook = new SXSSFWorkbook();
int page = list.size() % EXCEL_NUM_LIMIT == 0 ? list.size() / EXCEL_NUM_LIMIT : list.size() / EXCEL_NUM_LIMIT + 1;
log.info("sheet數量為:{}", page);
for (int m = 0; m < page; m++) {
Field[] fields = cls.getDeclaredFields();
ArrayList<String> headList = new ArrayList<>();
for (Field f : fields) {
ExcelField field = f.getAnnotation(ExcelField.class);
if (field != null) {
headList.add(field.title());
}
}
CellStyle style = getCellStyle(workBook);
Sheet sheet = workBook.createSheet();
workBook.setSheetName(m, "sheet" + String.valueOf(m + 1));
Header header = sheet.getHeader();
header.setCenter("sheet");
// 設置Excel表的第一行即表頭
Row row = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
Cell headCell = row.createCell(i);
headCell.setCellType(CellType.STRING);
headCell.setCellStyle(style);//設置表頭樣式
headCell.setCellValue(String.valueOf(headList.get(i)));
sheet.setColumnWidth(i, 15 * 256);
}
int rowIndex = 1;
log.info("開始創建sheet{}", m);
int start = (EXCEL_NUM_LIMIT * m);
int end = list.size() - start >= EXCEL_NUM_LIMIT ? start + EXCEL_NUM_LIMIT : list.size();
log.info("開始{},結束{}", start, end);
for (int i = start; i < end; i++) {
Row rowData = sheet.createRow(rowIndex);//創建數據行
T q = list.get(i);
Field[] ff = q.getClass().getDeclaredFields();
int j = 0;
for (Field f : ff) {
ExcelField field = f.getAnnotation(ExcelField.class);
if (field == null) {
continue;
}
f.setAccessible(true);
Object obj = null;
try {
obj = f.get(q);
} catch (IllegalAccessException e) {
log.error("", e);
}
Cell cell = rowData.createCell(j);
cell.setCellType(CellType.STRING);
// 當數字時
if (obj instanceof Integer) cell.setCellValue((Integer) obj);
// 當Long時
if (obj instanceof Long) cell.setCellValue((Long) obj);
// 當為字元串時
if (obj instanceof String) cell.setCellValue((String) obj);
// 當為布爾時
if (obj instanceof Boolean) cell.setCellValue((Boolean) obj);
// 當為時間時
if (obj instanceof Date) cell.setCellValue(getFormatDate((Date) obj));
// 當為時間時
if (obj instanceof Calendar) cell.setCellValue((Calendar) obj);
// 當為小數時
if (obj instanceof Double) cell.setCellValue((Double) obj);
// 當為BigDecimal
if (obj instanceof BigDecimal) cell.setCellValue(Double.parseDouble(obj.toString()));
// 當ZonedDateTime
if (obj instanceof ZonedDateTime)
cell.setCellValue(((ZonedDateTime) obj).format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")));
j++;
}
rowIndex++;
}
}
responseStream(workBook, response, fileName);
}
private static void responseStream(SXSSFWorkbook workBook, HttpServletResponse response, String fileName) {
OutputStream outputStream = null;
try {
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes("UTF-8"), "ISO-8859-1"));
response.setCharacterEncoding("utf-8");
//根據傳進來的file對象創建可寫入的Excel工作薄
outputStream = response.getOutputStream();
log.info("數據導出Excel成功!");
workBook.write(outputStream);
} catch (IOException e) {
log.error("", e);
} finally {
try {
outputStream.close();
} catch (IOException e) {
log.error("", e);
}
}
}
/**
* 設置表頭樣式
*
* @param wb
* @return
*/
public static CellStyle getCellStyle(SXSSFWorkbook wb) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName("宋體");
font.setFontHeightInPoints((short) 12);//設置字體大小
font.setBold(true);//加粗
style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());// 設置背景色
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setAlignment(HorizontalAlignment.CENTER);//讓單元格居中
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);// 左右居中
style.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
style.setWrapText(true);//設置自動換行
style.setFont(font);
return style;
}
public static String getFormatDate(Date date) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}
}
❺ Java POI操作Excel文件,打開該文件然後關閉時的保存問題
同問同問,有木有人遇到過,並解決了的?
已經解決:在setSheet的值後,加入workBook.getCreationHelper().createFormulaEvaluator().evaluateAll();即可
❻ java操作poi怎麼更改excel中的數據
POI里可能沒有這個機能。 不過你可以這樣做。 把帶有這個格式的Excel文件,做為模板。 每次把模板文件讀進來,把自己要輸出的數據填到對應的單元格里。 之後,把填完數據的Excel文件,保存到指定路徑里。或者從瀏覽器里彈出。
❼ java操作poi怎麼更改excel中的數據
修改完需要寫入,也就是保存一下的。
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;
public class ChangeCell {
@SuppressWarnings("deprecation")
public static void main(String[] args) {
String fileToBeRead = "C:\\exp.xls"; // excel位置
int coloum = 1; // 比如你要獲取第1列
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
fileToBeRead));
HSSFSheet sheet = workbook.getSheet("Sheet1");
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow((short) i);
if (null == row) {
continue;
} else {
HSSFCell cell = row.getCell((short) coloum);
if (null == cell) {
continue;
} else {
System.out.println(cell.getNumericCellValue());
int temp = (int) cell.getNumericCellValue();
cell.setCellValue(temp + 1);
}
}
}
FileOutputStream out = null;
try {
out = new FileOutputStream(fileToBeRead);
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
❽ java poi 操作excel 問題
首先回答你第一個問題:
讀取註解代碼如下:
Comment comment = sheet.getRow(7).getCell(5, Row.CREATE_NULL_AS_BLANK).getCellComment();
根據批註定位單元格做不到。。。
❾ java poi怎麼獲取excel單元格的內容
packagee.sjtu.erplab.poi;
importjava.io.InputStream&ch=ww.xqy.chain"target="_blank"class="link-ke">FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Map;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFDateUtil;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
*操作Excel表格的功能類
*/
publicclassExcelReader{
privatePOIFSFileSystemfs;
privateHSSFWorkbookwb;
privateHSSFSheetsheet;
privateHSSFRowrow;
/**
*讀取Excel表格表頭的內容
*@paramInputStream
*@returnString表頭內容的數組
*/
publicString[]readExcelTitle(InputStreamis){
try{
fs=newPOIFSFileSystem(is);
wb=newHSSFWorkbook(fs);
}catch(IOExceptione){
e.printStackTrace();
}
sheet=wb.getSheetAt(0);
row=sheet.getRow(0);
//標題總列數
intcolNum=row.getPhysicalNumberOfCells();
System.out.println("colNum:"+colNum);
String[]title=newString[colNum];
for(inti=0;i<colNum;i++){
//title[i]=getStringCellValue(row.getCell((short)i));
title[i]=getCellFormatValue(row.getCell((short)i));
}
returntitle;
}
/**
*讀取Excel數據內容
*@paramInputStream
*@returnMap包含單元格數據內容的Map對象
*/
publicMap<Integer,String>readExcelContent(InputStreamis){
Map<Integer,String>content=newHashMap<Integer,String>();
Stringstr="";
try{
fs=newPOIFSFileSystem(is);
wb=newHSSFWorkbook(fs);
}catch(IOExceptione){
e.printStackTrace();
}
sheet=wb.getSheetAt(0);
//得到總行數
introwNum=sheet.getLastRowNum();
row=sheet.getRow(0);
intcolNum=row.getPhysicalNumberOfCells();
//正文內容應該從第二行開始,第一行為表頭的標題
for(inti=1;i<=rowNum;i++){
row=sheet.getRow(i);
intj=0;
while(j<colNum){
//每個單元格的數據內容用"-"分割開,以後需要時用String類的replace()方法還原數據
//也可以將每個單元格的數據設置到一個javabean的屬性中,此時需要新建一個javabean
//str+=getStringCellValue(row.getCell((short)j)).trim()+
//"-";
str+=getCellFormatValue(row.getCell((short)j)).trim()+"";
j++;
}
content.put(i,str);
str="";
}
returncontent;
}
/**
*獲取單元格數據內容為字元串類型的數據
*
*@paramcellExcel單元格
*@returnString單元格數據內容
*/
(HSSFCellcell){
StringstrCell="";
switch(cell.getCellType()){
caseHSSFCell.CELL_TYPE_STRING:
strCell=cell.getStringCellValue();
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
strCell=String.valueOf(cell.getNumericCellValue());
break;
caseHSSFCell.CELL_TYPE_BOOLEAN:
strCell=String.valueOf(cell.getBooleanCellValue());
break;
caseHSSFCell.CELL_TYPE_BLANK:
strCell="";
break;
default:
strCell="";
break;
}
if(strCell.equals("")||strCell==null){
return"";
}
if(cell==null){
return"";
}
returnstrCell;
}
/**
*獲取單元格數據內容為日期類型的數據
*
*@paramcell
*Excel單元格
*@returnString單元格數據內容
*/
privateStringgetDateCellValue(HSSFCellcell){
Stringresult="";
try{
intcellType=cell.getCellType();
if(cellType==HSSFCell.CELL_TYPE_NUMERIC){
Datedate=cell.getDateCellValue();
result=(date.getYear()+1900)+"-"+(date.getMonth()+1)
+"-"+date.getDate();
}elseif(cellType==HSSFCell.CELL_TYPE_STRING){
Stringdate=getStringCellValue(cell);
result=date.replaceAll("[年月]","-").replace("日","").trim();
}elseif(cellType==HSSFCell.CELL_TYPE_BLANK){
result="";
}
}catch(Exceptione){
System.out.println("日期格式不正確!");
e.printStackTrace();
}
returnresult;
}
/**
*根據HSSFCell類型設置數據
*@paramcell
*@return
*/
(HSSFCellcell){
Stringcellvalue="";
if(cell!=null){
//判斷當前Cell的Type
switch(cell.getCellType()){
//如果當前Cell的Type為NUMERIC
caseHSSFCell.CELL_TYPE_NUMERIC:
caseHSSFCell.CELL_TYPE_FORMULA:{
//判斷當前的cell是否為Date
if(HSSFDateUtil.isCellDateFormatted(cell)){
//如果是Date類型則,轉化為Data格式
//方法1:這樣子的data格式是帶時分秒的:2011-10-120:00:00
//cellvalue=cell.getDateCellValue().toLocaleString();
//方法2:這樣子的data格式是不帶帶時分秒的:2011-10-12
Datedate=cell.getDateCellValue();
SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
cellvalue=sdf.format(date);
}
//如果是純數字
else{
//取得當前Cell的數值
cellvalue=String.valueOf(cell.getNumericCellValue());
}
break;
}
//如果當前Cell的Type為STRIN
caseHSSFCell.CELL_TYPE_STRING:
//取得當前的Cell字元串
cellvalue=cell.getRichStringCellValue().getString();
break;
//默認的Cell值
default:
cellvalue="";
}
}else{
cellvalue="";
}
returncellvalue;
}
publicstaticvoidmain(String[]args){
try{
//對讀取Excel表格標題測試
InputStreamis=newFileInputStream("d:\test2.xls");
ExcelReaderexcelReader=newExcelReader();
String[]title=excelReader.readExcelTitle(is);
System.out.println("獲得Excel表格的標題:");
for(Strings:title){
System.out.print(s+"");
}
//對讀取Excel表格內容測試
InputStreamis2=newFileInputStream("d:\test2.xls");
Map<Integer,String>map=excelReader.readExcelContent(is2);
System.out.println("獲得Excel表格的內容:");
for(inti=1;i<=map.size();i++){
System.out.println(map.get(i));
}
}catch(FileNotFoundExceptione){
System.out.println("未找到指定路徑的文件!");
e.printStackTrace();
}
}
}