java 热门问题讨论及解决方案,比如支付,单点登录,大批量excle导入,分布式事务等,大家都来讨论下呗,或者自己遇到的经典问题,最后都是怎么解决的
热门Java问题及解决方案:
package com.example.test;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ExcelReadTest {
/**
*根据文件路径得到MultipartFile
* @param url
* @return
* @throws IOException
*/
public MultipartFile fileToMultipartFile(String url) throws IOException {
File file = new File(url);
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
return multipartFile;
}
/**
* 将文件转化为可操作的类型
* @param multipartFile
* @return
* @throws IOException
*/
public Workbook getWorkFile(MultipartFile multipartFile) throws IOException {
Workbook workbook = null;
//获取文件的类型
String type = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);
//获取文件字节输入流
InputStream in = multipartFile.getInputStream();
if ("xls".equals(type)) {
workbook = new HSSFWorkbook(in);
} else if ("xlsx".equals(type)) {
workbook = new XSSFWorkbook(in);
}
return workbook;
}
/**
* 遍历读取excel的每一个单元格
* @param workbook
*/
public void readFile(Workbook workbook) {
//遍历sheet
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
//得到单个sheet
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
//得到单个sheet的行数
int rowCount = sheet.getLastRowNum();
//从第二行开始,遍历Sheet的每一行(第一行一般是标题,所以不遍历)
for (int rowNum = 1; rowNum <= rowCount; rowNum++) {
try {
//得到单行数据
Row row = sheet.getRow(rowNum);
if (row != null) {
int cellCount = row.getLastCellNum();
for (int cellNum = 0;cellNum<cellCount;cellNum++){
Cell cell = row.getCell(cellNum);
String cellValue = "";
if (cell!=null){
// cell.setCellType(CellType.STRING);//提前设置String类型,防止数字后加.0
// cellValue = cell.getStringCellValue();
//如果上面的setCellType(CellType.STRING)过期,可以先将Cell转化为CellBase,然后再定义类型
CellBase cellBase = (CellBase) cell;
//设置单元格数据类型
cellBase.setCellType(CellType.STRING);
//此处得到每一个单元格的值
cellValue = cellBase.getStringCellValue();
System.out.print("cellValue:" + cellValue+";");
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void excelUtil(String url) throws IOException {
MultipartFile multipartFile = fileToMultipartFile(url);
Workbook workbook = getWorkFile(multipartFile);
readFile(workbook);
}
public static void main(String[] args) throws IOException {
String file = "G:\\IDEAWorkspeace\\test\\excle\\src\\main\\resources\\excel\\试点团队配置模板.xls";
ExcelReadTest test = new ExcelReadTest();
test.excelUtil(file);
}
}