excel表格数据导入导出


/** * 导出数据到excel表格 * Created by shenjianhua on 2018-12-28 */
package com.luer.comm.excel;

import java.io.FileOutputStream;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.CellRangeAddress;import org.apache.poi.hssf.util.HSSFColor;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;

/** * 导出数据到excel表格 * Created by shenjianhua on 2018-12-28 */@RestController@RequestMapping("exportExcel")public class ExportexcelUtil {

/*    *    * 常用组件:

HSSFWorkbook    excel的文档对象

HSSFSheet       excel的表单

HSSFRow        excel的行

HSSFCell       excel的格子单元

HSSFFont        excel字体

样式:

HSSFCellStyle    cell样式    *    * */    public static void main(String [] args) throws Exception {

//excel的表单名        String sheetName = "操作员数据表1";        //excel的标题名        String titleName = "操作员数据表2";        //提示 没啥用        String fileName = "操作员数据表3";        //int columnNumber = 3;        int columnNumber = 9;        //int[] columnWidth = { 10, 20, 30 };        //int[] columnWidth = {40,20,20,20,20,20,20,20,20};        String[][] dataList = { { "4e7a2bbe5cc24a63b214b3824596cd543","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "4e7a2bbe5cc24a63b214b38296cd543","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg" },                { "9198a9f1acf74b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf14b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf24b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf34b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf44b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf54b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf64b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf84b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acf94b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"},                { "9198a9f1acfw4b648b50eee69d312276","2018-12-27 10:34:19","2018-12-27 10:34:19","usernamedsfsdsf","passwrodsdlkjflsd","nicknamesdgfds","18896876323","1324325432.qq.com","remarkdsgfdg"}        };        String[] columnName = { "操作员id", "创造时间", "更新时间","登录账号","登录密码","昵称","手机号码","邮箱","注释" };        new ExportexcelUtil().ExportNoResponse(sheetName, titleName,                columnNumber, /*columnWidth,*/ columnName, dataList, fileName);    }    /*    * 导出数据到excel表格    * */

/*    * String titleName: excel标题名    *    * String sheetName: excel表单名    *    * int columnNumber: excel标题名的数量    *    * String[] columnName:excel标题名成    *    * String[][] dataList: 导入的数据集合    * */

@RequestMapping("/export")    public void ExportNoResponse( String titleName,String sheetName,                                  int columnNumber, /*int[] columnWidth,*/                                 String[] columnName, String[][] dataList,String fileName) throws Exception {        int flag = 0;        int[] columnWidth=new int[columnNumber];        for(flag=0;flag<columnNumber;flag++){            if(flag==0){                columnWidth[flag] = 40;                //System.out.println("columnWidth[i]: "+columnWidth[flag]);            }else{

columnWidth[flag] = 30;                //System.out.println("columnWidth[i]: "+columnWidth[flag]);            }        }

if (columnNumber == columnWidth.length&& columnWidth.length == columnName.length) {            // 第一步,创建一个webbook,对应一个Excel文件            HSSFWorkbook wb = new HSSFWorkbook();            // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet            HSSFSheet sheet = wb.createSheet(sheetName);            // sheet.setDefaultColumnWidth(15); //统一设置列宽            for (int i = 0; i < columnNumber; i++)            {                for (int j = 0; j <= i; j++)                {                    if (i == j)                    {                        sheet.setColumnWidth(i, columnWidth[j] * 256); // 单独设置每列的宽                    }                }            }            // 创建第0行 也就是标题            HSSFRow row1 = sheet.createRow((int) 0);            row1.setHeightInPoints(50);// 设备标题的高度            // 第三步创建标题的单元格样式style2以及字体样式headerFont1            HSSFCellStyle style2 = wb.createCellStyle();            style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);            style2.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);            style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);            HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式            headerFont1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗            headerFont1.setFontName("黑体"); // 设置字体类型            headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小            style2.setFont(headerFont1); // 为标题样式设置字体样式

HSSFCell cell1 = row1.createCell(0);// 创建标题第一列            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,                    columnNumber - 1)); // 合并第0到第17列            cell1.setCellValue(titleName); // 设置值标题            cell1.setCellStyle(style2); // 设置标题样式

// 创建第1行 也就是表头            HSSFRow row = sheet.createRow((int) 1);            row.setHeightInPoints(37);// 设置表头高度

// 第四步,创建表头单元格样式 以及表头的字体样式            HSSFCellStyle style = wb.createCellStyle();            style.setWrapText(true);// 设置自动换行            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

style.setBottomBorderColor(HSSFColor.BLACK.index);            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);            style.setBorderRight(HSSFCellStyle.BORDER_THIN);            style.setBorderTop(HSSFCellStyle.BORDER_THIN);

HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗            headerFont.setFontName("黑体"); // 设置字体类型            headerFont.setFontHeightInPoints((short) 10); // 设置字体大小            style.setFont(headerFont); // 为标题样式设置字体样式

// 第四.一步,创建表头的列            for (int i = 0; i < columnNumber; i++)            {                HSSFCell cell = row.createCell(i);                cell.setCellValue(columnName[i]);                cell.setCellStyle(style);            }

// 第五步,创建单元格,并设置值            for (int i = 0; i < dataList.length; i++)            {                row = sheet.createRow((int) i + 2);                // 为数据内容设置特点新单元格样式1 自动换行 上下居中                HSSFCellStyle zidonghuanhang = wb.createCellStyle();                zidonghuanhang.setWrapText(true);// 设置自动换行                zidonghuanhang                        .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个居中格式

// 设置边框                zidonghuanhang.setBottomBorderColor(HSSFColor.BLACK.index);                zidonghuanhang.setBorderBottom(HSSFCellStyle.BORDER_THIN);                zidonghuanhang.setBorderLeft(HSSFCellStyle.BORDER_THIN);                zidonghuanhang.setBorderRight(HSSFCellStyle.BORDER_THIN);                zidonghuanhang.setBorderTop(HSSFCellStyle.BORDER_THIN);

// 为数据内容设置特点新单元格样式2 自动换行 上下居中左右也居中                HSSFCellStyle zidonghuanhang2 = wb.createCellStyle();                zidonghuanhang2.setWrapText(true);// 设置自动换行                zidonghuanhang2                        .setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个上下居中格式                zidonghuanhang2.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中

// 设置边框                zidonghuanhang2.setBottomBorderColor(HSSFColor.BLACK.index);                zidonghuanhang2.setBorderBottom(HSSFCellStyle.BORDER_THIN);                zidonghuanhang2.setBorderLeft(HSSFCellStyle.BORDER_THIN);                zidonghuanhang2.setBorderRight(HSSFCellStyle.BORDER_THIN);                zidonghuanhang2.setBorderTop(HSSFCellStyle.BORDER_THIN);                HSSFCell datacell = null;                for (int j = 0; j < columnNumber; j++)                {                    datacell = row.createCell(j);                    datacell.setCellValue(dataList[i][j]);                    datacell.setCellStyle(zidonghuanhang2);                }            }

// 第六步,将文件存到指定位置            try {                FileOutputStream fout = new FileOutputStream("D:operator.xls");                wb.write(fout);                String str = "导出" + fileName + "成功!";                System.out.println(str);                fout.close();            } catch (Exception e) {                e.printStackTrace();                String str1 = "导出" + fileName + "失败!";                System.out.println(str1);            }        } else {            System.out.println("列数目长度名称三个数组长度要一致");        }

}

}
/** * Excel 导入到mysql * Created by shenjianhua on 2018-12-28 */
package com.luer.comm.excel;

import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;

import com.luer.operator.bean.Operator;import com.luer.operator.service.OperatorService;import org.apache.log4j.Logger;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;

/** * Excel 导入到mysql * Created by shenjianhua on 2019-1-3 */@RestController@RequestMapping("/importExcel")public class ImportexcelUtil {

private static Logger logger = Logger.getLogger(ImportexcelUtil.class);    private final static String xls = "xls";    private final static String xlsx = "xlsx";

/**     * 读入excel文件,解析后返回     *     * @param     * @throws IOException     */

@Autowired    OperatorService operatorService;

/*    * 读取excel数据导入数据库    * */    @ResponseBody    @RequestMapping("/readExcel")    public List<String[]> readExcel(MultipartFile file) throws Exception {        //检查文件        checkFile(file);        //获得Workbook工作薄对象        Workbook workbook = getWorkBook(file);        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回        List<String[]> list = new ArrayList<String[]>();        if (workbook != null) {            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {                //获得当前sheet工作表                Sheet sheet = workbook.getSheetAt(sheetNum);                if (sheet == null) {                    continue;                }                //获得当前sheet的开始行                int firstRowNum = sheet.getFirstRowNum();                //获得当前sheet的结束行                int lastRowNum = sheet.getLastRowNum();                //循环除了第一行的所有行                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {                    //获得当前行                    Row row = sheet.getRow(rowNum);                    if (row == null) {                        continue;                    }                    //获得当前行的开始列                    int firstCellNum = row.getFirstCellNum();                    //获得当前行的列数                    int lastCellNum = row.getPhysicalNumberOfCells();                    String[] cells = new String[row.getPhysicalNumberOfCells()];                    //循环当前行                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {                        Cell cell = row.getCell(cellNum);                        cells[cellNum] = getCellValue(cell);                    }                    list.add(cells);                }

}            //workbook.close();        }

/*        * 封装对象存入数据库        *         * 修改字段的遍历次数        * */        for(int k=1;k<9;k++) {            Operator operator = new Operator();            if(null != list.get(k)[0]){                operator.setId(list.get(k)[0]);            }            if(null != list.get(k)[1]){                operator.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(list.get(k)[1]));               /* String string = "2016-10-24 21:59:06";                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");                System.out.println(sdf.parse(list.get(k)[1]));*/            }            if(null != list.get(k)[2]){                operator.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(list.get(k)[1]));            }            if(null != list.get(k)[3]){                operator.setUsername(list.get(3)[3]);            }            if(null != list.get(k)[4]){                operator.setPassword(list.get(k)[4]);            }            if(null != list.get(k)[5]){                operator.setNickname(list.get(k)[5]);            }            if(null != list.get(k)[6]){                operator.setPhoneNumber(list.get(k)[6]);            }            if(null != list.get(k)[7]){                operator.setEmail(list.get(k)[8]);            }            if(null != list.get(k)[8]){                operator.setRemark(list.get(k)[8]);            }            operatorService.insertOperator(operator);        }

return list;    }

@ResponseBody    @RequestMapping("/readExcel2")    public String[] readExcel2(MultipartFile file) throws IOException {        //检查文件        checkFile(file);        //获得Workbook工作薄对象        Workbook workbook = getWorkBook(file);        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回        List<String[]> list = new ArrayList<String[]>();        if (workbook != null) {            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {                //获得当前sheet工作表                Sheet sheet = workbook.getSheetAt(sheetNum);                if (sheet == null) {                    continue;                }                //获得当前sheet的开始行                int firstRowNum = sheet.getFirstRowNum();                //获得当前sheet的结束行                int lastRowNum = sheet.getLastRowNum();                //循环除了第一行的所有行                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {                    //获得当前行                    Row row = sheet.getRow(rowNum);                    if (row == null) {                        continue;                    }                    //获得当前行的开始列                    int firstCellNum = row.getFirstCellNum();                    //获得当前行的列数                    int lastCellNum = row.getPhysicalNumberOfCells();                    String[] cells = new String[row.getPhysicalNumberOfCells()];                    //循环当前行                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {                        Cell cell = row.getCell(cellNum);                        cells[cellNum] = getCellValue(cell);                    }                    list.add(cells);                }            }            // workbook.close();        }

return list.get(0);    }

public static void checkFile(MultipartFile file) throws IOException {        //判断文件是否存在        if (null == file) {            logger.error("文件不存在!");            throw new FileNotFoundException("文件不存在!");        }        //获得文件名        String fileName = file.getOriginalFilename();        //判断文件是否是excel文件        if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)) {            logger.error(fileName + "不是excel文件");            throw new IOException(fileName + "不是excel文件");        }    }

public static Workbook getWorkBook(MultipartFile file) {        //获得文件名        String fileName = file.getOriginalFilename();        //创建Workbook工作薄对象,表示整个excel        Workbook workbook = null;        try {            //获取excel文件的io流            InputStream is = file.getInputStream();            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象            if (fileName.endsWith(xls)) {                //2003                workbook = new HSSFWorkbook(is);            } else if (fileName.endsWith(xlsx)) {                //2007 及2007以上                workbook = new XSSFWorkbook(is);            }        } catch (IOException e) {            logger.info(e.getMessage());        }        return workbook;    }

public static String getCellValue(Cell cell) {        String cellValue = "";        if (cell == null) {            return cellValue;        }        //把数字当成String来读,避免出现1读成1.0的情况        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {            cell.setCellType(Cell.CELL_TYPE_STRING);        }        //判断数据的类型        switch (cell.getCellType()) {            case Cell.CELL_TYPE_NUMERIC: //数字                cellValue = String.valueOf(cell.getNumericCellValue());                break;            case Cell.CELL_TYPE_STRING: //字符串                cellValue = String.valueOf(cell.getStringCellValue());                break;            case Cell.CELL_TYPE_BOOLEAN: //Boolean                cellValue = String.valueOf(cell.getBooleanCellValue());                break;            case Cell.CELL_TYPE_FORMULA: //公式                cellValue = String.valueOf(cell.getCellFormula());                break;            case Cell.CELL_TYPE_BLANK: //空值                cellValue = "";                break;            case Cell.CELL_TYPE_ERROR: //故障                cellValue = "非法字符";                break;            default:                cellValue = "未知类型";                break;        }        return cellValue;    }}

如果帮助到你 给点鼓励 点个赞吧 谢谢亲

原文地址:https://www.cnblogs.com/shenhaha520/p/10214508.html

时间: 2024-09-30 18:41:24

excel表格数据导入导出的相关文章

将包含经纬度点位信息的Excel表格数据导入到ArcMap中并输出成shapefile

将包含经纬信息的Excel表格数据,导入到ArcMap中并输出成shapefile,再进行后面的操作.使用这种方法可以将每一个包含经纬信息的数据在ArcMap中点出来. 一.准备数据 新建Excel表格,保存时设置后缀名为.xls(即2003Excel的表格).在表格首行建立各字段名,其中要包含经度和纬度的信息,用于在地图中标定位置.录入各记录属性,整理成表. 二.ArcMap中添加x-y事件 在打开的对话框中选择数据表和x.y对应的经度.纬度.选择坐标系统,这里因为我们的x,y对应的数据是经纬

用多线程优化Excel表格数据导入校验的接口

公司的需求,当前某个Excel导入功能,流程是:读取Excel数据,传入后台校验每一条数据,判断是否符合导入要求,返回给前端,导入预览展示.(前端等待响应,难点).用户再点击导入按钮,进行异步导入(前端不等待,好做).当前接口仅支持300条数据,现在要求我要支持3000条数据. 解决问题,思路是关键. 首先,查看接口,找到读取表格的位置,看到判断,如果数据量大于300,直接返回.把300改成3000. 然后,分析导入数据校验,都是和哪些数据进行校验的,这些数据都是从数据库来的.每一次都从数据库查

Excel表格的导入导出

excel.Application app = new excel.Application(); app.SheetsInNewWorkbook = 2; app.Workbooks.Add(); Worksheet sheet1 = (Worksheet)app.ActiveWorkbook.Worksheets[1]; sheet1.Name = "Hello Word"; sheet1.Cells[1, 1] = "Welcome To Excel"; Wor

Excel表格数据导入到SQLServer数据库

转载:http://blog.csdn.net/lishuangzhe7047/article/details/8797416 步骤: 1,选择要插入的数据库--右键--任务--导入数据 2,点击下一步,选择数据源,excel文件路径,和版本信息(注:使用2010及以上版本的office,请先将格式转换为03 或07格式的以便识别) 3,选择目标数据库 4,执行成功 5,查看导入数据,可以重命名 以上就是数据库导入excel文件的步骤,数据库导出数据同理. 很多系统都给我们做好了不同格式文件的导

PHPexcel 将excel表格数据导入数据库

// index.php<form name="frm1" enctype="multipart/form-data" action="insertdb.php" method="post">   <input name="filename" type="file" /><input name="submit" type="su

VUE前端如何实现Excel表格的导入导出?

exportOpera(res, fileName, flag) { const self = this; let content; let blob; if (Object.prototype.toString.call(res) === "[object Function]") { content = res(); const fr = new FileReader(); blob = new Blob([content]); fr.readAsText(blob); fr.onl

Unity —— protobuf 导excel表格数据

前言: 之前使用NPOI插件编写的导表工具,其实就是直接将数据进行序列化,解析时还需要进行反序列化,步骤比较繁复,最近看到Google的一个开源的项目protobuf,不仅可以用于进行excel表格数据的导出,还能直接用于网络通信协议的定制. 一.protobuf简介: protobuf是由google公司发布的一个开源的项目,是一款方便而又通用的数据传输协议.所以我们在Unity中也可以借助protobuf来进行数据存储和网络协议两方面的开发,这里先说说数据存储部分的操作,也就是: 将.xls

使用pentaho工具将数据库数据导入导出为Excel

写在前面:本篇博客讲述的是如何使用pentaho工具快速的将数据库数据导出为Excel文件,以及如何将Excel文件数据导入数据库. 补充:使用此工具并不需要任何一句代码并能快速便捷解决实际问题,此工具功能不仅仅局限这一点,其他功能后续更新. 工具下载:你可以根据你电脑的系统选择不同版本在pentaho官网进行下载: http://www.pentaho.com/download 需求一:将mysql一张表数据导出到Excel 第一步:添加数据库驱动包 注意:由于本例我要将mysql数据库数据导

excel数据导入导出数据库

第一种方法: 先把Excel另存为.csv格式文件,如test.csv,再编写一个insert.ctl 用sqlldr进行导入! insert.ctl内容如下: load data          --1.控制文件标识 infile ‘my.csv‘          --2.要输入的数据文件名为my.csv append into table "tbl_test"   --3.向表table_name中追加记录 fields terminated by ‘,‘