SpringBoot導入導出Excel簡單小例子

首先添加依賴。

<!--文件上傳組件-->

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.1</version>

</dependency>

<dependency>

<groupId>commons-io</groupId>

<artifactId>commons-io</artifactId>

<version>2.5</version>

</dependency>

<!--讀取excel文件-->

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.17</version>

</dependency>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.17</version>

</dependency>

然后寫數(shù)據(jù)庫對應的實體類

然后mapper層,有一個查詢方法辕万,有一個添加方法。

然后是mapper映射文件铝阐,業(yè)務層。這里就不列舉了脚翘。

重點說一下controller。


@Controller

public class SaleController {

@Autowired

? ? private SaleServiceImpltt;

//這一個方法是查詢出數(shù)據(jù)顯示到freemark頁面

@RequestMapping("/index")

public? String select(Model model, Integer id, Integer price, Integer quantity, Integer totalPrice,Integer userId, Integer productId){

List list=tt.select(id,price,quantity,totalPrice,userId,productId);

model.addAttribute("list",list);

return "index";

}

//這是個是導入文件

@RequestMapping("/excel/upload")

public String fileUpload(@RequestParam("file") MultipartFile file,Integer price,Integer quantity,Integer totalPrice,Integer userId,Integer productId)throws IOException {

long size=file.getSize();

HSSFWorkbook workbook =new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));

//獲得有多少sheet

? ? ? ? int numberOfSheets = workbook.getNumberOfSheets();

//默認只有一個sheet

? ? ? ? HSSFSheet sheet = workbook.getSheetAt(0);

//獲得sheet有多少行

? ? ? ? int rows = sheet.getPhysicalNumberOfRows();

//遍歷行

? ? ? ? for (int j =0; j < rows; j++) {

if (j ==0) {

continue;//標題行(省略)

? ? ? ? ? ? }

for (int k =0; k <1; k++) {

//這個循環(huán)是這個表格有多少行绍哎,就循環(huán)多少次来农,每次循環(huán)都會獲得除了id那一列的每一列數(shù)據(jù)(id為遞增,不需要添加)崇堰,因為我的數(shù)據(jù)全都是int類型沃于,但是獲取的是double類型,所以我把它轉(zhuǎn)化為了int類型海诲。row.getcell()是獲取列,?two.getNumericCellValue()是獲取這個列的這個數(shù)據(jù),然后調(diào)用insert()方法繁莹,最后插入進數(shù)據(jù)庫。

HSSFRow row = sheet.getRow(j);

HSSFCell two = row.getCell(1);

HSSFCell three = row.getCell(2);

HSSFCell four = row.getCell(3);

HSSFCell five = row.getCell(4);

HSSFCell six = row.getCell(5);

double twoa = two.getNumericCellValue();

int twob = (int) twoa;

double threea = three.getNumericCellValue();

int threeb = (int) threea;

double foura = four.getNumericCellValue();

int fourb = (int) foura;

double fivea = five.getNumericCellValue();

int fiveb = (int) fivea;

double sixa = six.getNumericCellValue();

int sixb = (int) sixa;

tt.insert(twob, threeb, fourb, fiveb, sixb);

}

}

return "poi";

}

//生成user表excel

? ? @GetMapping(value ="/excel/getUser")

@ResponseBody

? ? public String getUser(HttpServletResponse response,Integer id,Integer price,Integer quantity,Integer totalPrice,Integer userId,Integer productId)throws Exception{

HSSFWorkbook workbook =new HSSFWorkbook();

HSSFSheet sheet = workbook.createSheet("統(tǒng)計表");

createTitle(workbook,sheet);

//userService.getAll();

//而導出方法首先要查詢出來數(shù)據(jù)庫里面的數(shù)據(jù)饿肺,存到rows中蒋困,然后設置生成excel表的格式,把數(shù)據(jù)庫查詢出來的數(shù)據(jù)插入進去敬辣。

? ? ? List rows=tt.select(id,price,quantity,totalPrice,userId,productId);

System.out.print("aaaaaaaaaaaa"+rows);

HSSFCellStyle style = workbook.createCellStyle();

style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

//新增數(shù)據(jù)行,并且設置單元格數(shù)據(jù)

? ? ? ? int rowNum=1;

for(Sale user:rows){

HSSFRow row = sheet.createRow(rowNum);

row.createCell(0).setCellValue(user.getId());

row.createCell(1).setCellValue(user.getPrice());

row.createCell(2).setCellValue(user.getProductId());

row.createCell(3).setCellValue(user.getQuantity());

row.createCell(4).setCellValue(user.getUserId());

rowNum++;

}

String fileName ="導出excel例子.xls";

//生成excel文件

? ? ? ? buildExcelFile(fileName, workbook);

//瀏覽器下載excel

? ? ? ? buildExcelDocument(fileName,workbook,response);

return "Poi";

}

//創(chuàng)建表頭

? ? private void createTitle(HSSFWorkbook workbook,HSSFSheet sheet){

HSSFRow row = sheet.createRow(0);

//設置列寬零院,setColumnWidth的第二個參數(shù)要乘以256溉跃,這個參數(shù)的單位是1/256個字符寬度

? ? ? ? sheet.setColumnWidth(1,12*256);

sheet.setColumnWidth(3,17*256);

//設置為居中加粗

? ? ? ? HSSFCellStyle style = workbook.createCellStyle();

HSSFFont font = workbook.createFont();

font.setBold(true);

//style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

? ? ? ? style.setFont(font);

HSSFCell cell;

cell = row.createCell(0);

cell.setCellValue("id");

cell.setCellStyle(style);

cell = row.createCell(1);

cell.setCellValue("price");

cell.setCellStyle(style);

cell = row.createCell(2);

cell.setCellValue("quantity");

cell.setCellStyle(style);

cell = row.createCell(3);

cell.setCellValue("totalprice");

cell = row.createCell(4);

cell.setCellValue("userId");

cell = row.createCell(5);

cell.setCellValue("productId");

cell.setCellStyle(style);

}

//生成excel文件

? ? protected void buildExcelFile(String filename,HSSFWorkbook workbook)throws Exception{

FileOutputStream fos =new FileOutputStream(filename);

workbook.write(fos);

fos.flush();

fos.close();

}

//瀏覽器下載excel

? ? protected void buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response)throws Exception{

response.setContentType("application/vnd.ms-excel");

response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));

OutputStream outputStream = response.getOutputStream();

workbook.write(outputStream);

outputStream.flush();

outputStream.close();

}

然后最后寫ftl頁面

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

</head>

<body>

<table border="1">

<tr>

<th>用戶名</th>

<th>價格</th>

<th>數(shù)量</th>

<th>總價</th>

<th>銷售者id</th>

<th>銷售產(chǎn)品id</th>

</tr>

<#list list as item>

? ? <tr >

<td >${item.id}</td>

<td >${item.price}</td>

<td >${item.quantity}</td>

<td >${item.totalPrice}</td>

<td >${item.userId}</td>

<td >${item.productId}</td>

</tr>


</table>

<button onclick="location.href='http://localhost:8080//excel/getUser';">導出</button>

<h1>這是用戶信息頁</h1>

//這個from表單就是選擇excel文件,上傳到excel/upload方法里面告抄。

<form action="excel/upload" method="post" enctype="multipart/form-data">

<input name="file" type="file" />

<input type="submit"/>

</form>

</body>

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末撰茎,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子打洼,更是在濱河造成了極大的恐慌龄糊,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件募疮,死亡現(xiàn)場離奇詭異炫惩,居然都是意外死亡,警方通過查閱死者的電腦和手機阿浓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門他嚷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人芭毙,你說我怎么就攤上這事筋蓖。” “怎么了退敦?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵粘咖,是天一觀的道長。 經(jīng)常有香客問我侈百,道長瓮下,這世上最難降的妖魔是什么忠聚? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮唱捣,結(jié)果婚禮上两蟀,老公的妹妹穿的比我還像新娘。我一直安慰自己震缭,他們只是感情好赂毯,可當我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著拣宰,像睡著了一般党涕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上巡社,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天膛堤,我揣著相機與錄音,去河邊找鬼晌该。 笑死肥荔,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的朝群。 我是一名探鬼主播燕耿,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼姜胖!你這毒婦竟也來了誉帅?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤右莱,失蹤者是張志新(化名)和其女友劉穎蚜锨,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體慢蜓,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡亚再,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了胀瞪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片针余。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖凄诞,靈堂內(nèi)的尸體忽然破棺而出圆雁,到底是詐尸還是另有隱情,我是刑警寧澤帆谍,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布伪朽,位于F島的核電站,受9級特大地震影響汛蝙,放射性物質(zhì)發(fā)生泄漏烈涮。R本人自食惡果不足惜朴肺,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望坚洽。 院中可真熱鬧戈稿,春花似錦、人聲如沸讶舰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽跳昼。三九已至般甲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間鹅颊,已是汗流浹背敷存。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留堪伍,地道東北人锚烦。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像杠娱,于是被迫代替她去往敵國和親挽牢。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容