1.首先导入poi包
2.这里struts2的框架上传文件
前台界面:
public class UploadFileAction extends JqgridAction {
private File excel; // 上传的文件
private String excelFileName; // 文件名称
private String excelContentType; // 文件类型
private INewShopRpnhAddService newShopRpnhAddService;
private ISimpleGoodsService simpleGoodsService;
private ISimpleShopInfoService simpleShopInfoService;
private IGoodsStockB2BService goodsStockB2BService;
private List<String> exportInfo = new ArrayList<String>();
public void exportExcel() {
if (excuteExcel()) {
XSSFSheet sheet = null;
User user = (User) StrutsUtils.getSession().getAttribute(Constant.CRLSESSION);
String shopNo = user.getShopId();
sheet = getXSSFSheet();
XSSFRow row;
String sku;
int qty = 0;
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row != null) {
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
sku = row.getCell(0).getStringCellValue().trim();
row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
String temqty = row.getCell(1).getStringCellValue().trim();
qty = Integer.valueOf(temqty);
saveOrUpdate(qty, shopNo, sku);
}
}
exportInfo.add("恭喜你,导入数据成功!!!");
} else {
exportInfo.add("对不起,导入失败!!!");
}
JSONObject json = new JSONObject();
json.put("exportInfo", exportInfo);
try {
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().write(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @author Solor
* @deprecated 将上传文件保存到服务器里面
* @param uploadPath
* @param fileName
* @throws IOException
*/
private void saveFile(String uploadPath, String fileName) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
// 创建一个输入流
is = new FileInputStream(excel);
File file = new File(uploadPath);
if (!file.exists())
file.mkdirs();
// 创建目标文件
File toFile = new File(uploadPath, fileName);
toFile.createNewFile();
// 创建一个输出流
os = new FileOutputStream(toFile);
// 设置缓存
byte[] buffer = new byte[2048];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入流
is.close();
// 关闭输出流
os.close();
}
}
}
上面的代码这里删除了大量和主题无关的代码,只保留和excel导入相关的代码。