本文目录一览:
- 1、如何用java完成Excel快速的导入导出
- 2、java开发怎么导入导出excel里面信息内容?
- 3、怎么用java实现mysql数据库的导入导出
- 4、java如何实现导入和导出功能
- 5、java使用什么技术实现excel数据的批量导入导出
- 6、如何用java实现mysql数据库的导入导出
如何用java完成Excel快速的导入导出
导出
现在我们定义好对象了,如何导出Excel --ExcelExportUtil 这个导出工具类
public void testExportExcel_1() throws Exception {
ExportParams params = new ExportParams("0328课程表", "日期:2016-03-28", "六年一班");
Workbook workbook = ExcelExportUtil.exportExcel(params, CourseEntity.class,courseList);
FileOutputStream fos = new FileOutputStream("D:/excel/0328课程表.xls");
workbook.write(fos);
fos.close();
}
我们只要把我们定义好的对象的class传进去,以及对象的集合,Easypoi就可以返回一个Excel的workbook了,同时Easypoi是兼容03版本office和07版本office,你要穿个参数指定下类型及可以了,是不是不是比我们自己写代码简单多了,最少只需要2行代码就可以完成我们的office操作了
导入
我们把导出写完了,导入是不是很复杂呢,也不是,导入也是同样简单,定时实体和上面定义的方式一样
导入是用导入工具类
ImportParams params = new ImportParams();
params.setHeadRows(2);
ListCourseEntity list = ExcelImportUtil.importExcel(inputStream, CourseEntity.class, params);
定义下表头的参数,然后把流传入进去就可以得到我们的对象列表是不是so easy.赶快来使用吧
java开发怎么导入导出excel里面信息内容?
public class ExcelExport {
/**
* 默认每个sheet页最多显示的行数
*/
private static final int sheet_rows = 50000;
/**
* 导出Excel文件
*
* @param titleList
* 表头信息
* @param dataList
* 表格数据
* @param fileName
* 导出文件完整名称 demo.xls
* @param request
* @param response
* @throws IOException
*/
public static void exportExcelFile(ListString titleList,
ListListString dataList, String fileName,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
HSSFWorkbook workBook = exportDataToExcel(titleList, dataList);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
fileName = encodeFilename(fileName, request);
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
workBook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}
public static String encodeFilename(String filename, HttpServletRequest request) {
String agent = request.getHeader("USER-AGENT");
try {
if ((agent != null) ( 0 = agent.indexOf("Firefox"))) {
return MimeUtility.encodeText(filename, "UTF-8", "B");
} else if((agent != null) ( 0 = agent.indexOf("Chrome"))){
return filename = new String(filename.getBytes(), "ISO8859-1");
}
else {
if (agent != null) {
String newFileName = URLEncoder.encode(filename, "UTF-8");
newFileName = StringUtils.replace(newFileName, "+", "%20");
if (newFileName.length() 150) {
newFileName = new String(filename.getBytes("GB2312"),
"ISO8859-1");
newFileName = StringUtils.replace(newFileName, " ",
"%20");
}
return newFileName;
}
}
} catch (Exception ex) {
return filename;
}
return filename;
}
public static HSSFWorkbook exportDataToExcel(ListString titleList, ListListString dataList) {
/* 1.创建一个Excel文件 */
HSSFWorkbook workbook = new HSSFWorkbook();
/* 2.创建Excel的一个Sheet */
HSSFSheet sheet = workbook.createSheet();
/* 3.创建表头冻结 */
sheet.createFreezePane(0, 1);
/* 4.设置列宽 */
for (int i = 0; i titleList.size(); i++) {
sheet.setColumnWidth(i, 5000);
}
/* 5.表头字体 */
HSSFFont headfont = workbook.createFont();
headfont.setFontName("宋体");
headfont.setFontHeightInPoints((short) 12);// 字体大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
/* 6.表头样式 */
HSSFCellStyle headstyle = workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
// 设置背景色为蓝色
headstyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
headstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
/* 7.普通单元格字体 */
HSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);
/* 8.普通单元格样式 */
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
/* 9. 拼装表头 */
IteratorString titleRowIterator = titleList.iterator();
int columnIndex = 0;
HSSFRow row = sheet.createRow(0);
while (titleRowIterator.hasNext()) {
String cellValue = titleRowIterator.next();
HSSFCell cell = row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(headstyle);
columnIndex++;
cell = null;
}
/* 10.组织表数据 */
IteratorListString rowIterator = dataList.iterator();
int rowIndex = 1;
while (rowIterator.hasNext()) {
ListString columnList = rowIterator.next();
row = sheet.createRow(rowIndex);
IteratorString columnIterator = columnList.iterator();
columnIndex = 0;
while (columnIterator.hasNext()) {
String cellValue = columnIterator.next();
HSSFCell cell = row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(style);
cell = null;
columnIndex++;
}
row = null;
rowIndex++;
}
return workbook;
}
/**
* 重载导出数据到Excel中
* @param titleList 表头
* @param dataList 表数据
* @param amount 每个sheet页显示行数
* @return
*/
public static HSSFWorkbook exportDataToExcel(ListString titleList, ListListString dataList, int amount) {
/* 1.创建一个Excel文件 */
HSSFWorkbook workbook = new HSSFWorkbook();
//校验传入的参数
if(titleList==null){
titleList = new ArrayListString();
}
//无数据直接返回
if(dataList==null || dataList.size()==0){
return workbook;
}
//传入数据不正确,按照默认条数显示
if(amount65535 || amount=0){
amount = sheet_rows;
}
//获取sheet页的数量
int row_num = 0;
int y = dataList.size()%amount;
if(y == 0){
row_num = dataList.size()/amount;
}else{
row_num = dataList.size()/amount + 1;
}
/* 表头字体 */
HSSFFont headfont = workbook.createFont();
headfont.setFontName("宋体");
headfont.setFontHeightInPoints((short) 12);// 字体大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
/* 表头样式 */
HSSFCellStyle headstyle = workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
// 设置背景色为蓝色
headstyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
headstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
/* 普通单元格字体 */
HSSFFont font = workbook.createFont();
font.setFontName("宋体");
font.setFontHeightInPoints((short) 12);
/* 普通单元格样式 */
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
//循环写入每个sheet页
for(int i=0;irow_num;i++){
/* 创建Excel的一个Sheet */
HSSFSheet sheet = workbook.createSheet();
/* 创建表头冻结 */
sheet.createFreezePane(0, 1);
/* 设置列宽 */
for (int t = 0; t titleList.size(); t++) {
sheet.setColumnWidth(t, 5000);
}
/* 拼装表头 */
IteratorString titleRowIterator = titleList.iterator();
int columnIndex = 0;
HSSFRow row = sheet.createRow(0);
while (titleRowIterator.hasNext()) {
String cellValue = titleRowIterator.next();
HSSFCell cell = row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(headstyle);
columnIndex++;
cell = null;
}
/* 组织表数据 */
int rowIndex = 1;
for (int j=amount*i;(jamount*(i+1)jdataList.size());j++) {
ListString columnList = dataList.get(j);
row = sheet.createRow(rowIndex);
IteratorString columnIterator = columnList.iterator();
columnIndex = 0;
while (columnIterator.hasNext()) {
String cellValue = columnIterator.next();
HSSFCell cell = row.createCell(columnIndex);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(cellValue);
cell.setCellStyle(style);
cell = null;
columnIndex++;
}
row = null;
rowIndex++;
}
}
return workbook;
}
/**
* 重载导出Excel功能,新增一项amount每个sheet导出记录行数
* @param titleList
* @param dataList
* @param fileName
* @param amount 行数如果小于等于0或大于65535则按照默认显示
* @param request
* @param response
* @throws IOException
*/
public static void exportExcelFile(ListString titleList,
ListListString dataList, String fileName, int amount,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
HSSFWorkbook workBook = exportDataToExcel(titleList, dataList, amount);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("UTF-8");
fileName = encodeFilename(fileName, request);
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
workBook.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
说明:main方法里的第一个参数为要导出的表头信息,
第二个参数为数据信息,
第三个参数设置文件名,设置好以后直接调用就可以导出Excle了;
导入就是把文件存到服务器,可用Mogodb等数据库存储,以下是读取已存根据存储的文件id解析Excle数据的大致过程:
POIFSFileSystem fs = null;
if (!StringUtils.isBlank(fileId)) {
fs = new POIFSFileSystem(new ByteArrayInputStream(
//传入对应的文件对象
MongoFileUtil.readFile(fileId)));
}
// 构造 XSSFWorkbook 对象,filePath 传入文件路径
HSSFWorkbook xwb = new HSSFWorkbook(fs);
// 读取第一个sheet
HSSFSheet sheet = xwb.getSheetAt(0);
for (int i = sheet.getFirstRowNum() + 1; i sheet.getPhysicalNumberOfRows();i++){
//解析每行的数据
HSSFRow singleRow = sheet.getRow(i);
//解析每个单元格数据
singleRow.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
String cellValue= singleRow.getCell(0).getStringCellValue();
}
怎么用java实现mysql数据库的导入导出
使用Java实现对MySql数据库的导入与导出
package com.project.ajaxs;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.Date;
public class BakMysql {
//main的方法,主要是我用于测试的,是想着取得CLASS的路径,然后备份的文件写在服务器的类路径下
public static void main(String[] args) {
BakMysql bk = new BakMysql();
bk.backup();
// bk.load();
}
//backup方法是备份数据库到服务器地址
public void backup() {
Calendar now = Calendar.getInstance();
String name = now.getTime()+""+(now.getTime().getMonth()+1)+""+now.getTime().getDate();
String filename = name.substring(24)+" "+name.substring(11,13)+""+name.substring(14,16)+""+name.substring(17,19);
try {
String filePath ="e:/project"+filename+".sql";
Runtime rt = Runtime.getRuntime();
// 调用 mysql 的 cmd:
Process child = rt.exec("C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump.exe -uroot -p8095longchun project");// 设置导出编码为utf8。这里必须是utf8
//注意这一句,是指运行mysqldump命令,后面跟的是登录名和登录的密码,接着后面的是指备份的数据库的名字,到此结束,以此生成一个执行的进程,取得此进程的输出流到我们要备份的文件
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
InputStreamReader xx = new InputStreamReader(in, "utf-8");// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
// 组合控制台输出信息字符串
BufferedReader br = new BufferedReader(xx);
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();//备份出来的内容是一个字条串
// 要用来做导入用的sql目标文件:
FileOutputStream fout = new FileOutputStream(filePath);
OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
writer.write(outStr);//写文件
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
in.close();
xx.close();
br.close();
writer.close();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//数据库的导入
public void load() {
try {
String fPath = "e:/aa.sql";
Runtime rt = Runtime.getRuntime();
Process child = rt.exec("C:/Program Files/MySQL/MySQL Server 5.0/bin/mysqladmin.exe -uroot -p8095longchun create project");
Process child1 =rt.exec("C:/Program Files/MySQL/MySQL Server 5.0/bin/mysql.exe -uroot -p8095longchun project");
OutputStream out = child1.getOutputStream();//控制台的输入信息作为输出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fPath), "utf-8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
out.close();
br.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
原文来自
java如何实现导入和导出功能
看你要导入什么了,什么格式,是电话还是其他软件或者资料,只要兼容就能导入导出的。
java使用什么技术实现excel数据的批量导入导出
java使用第三方工具包POI技术实现excel数据的批量导入导出。
举例如下:
1、下载apache的相关jar包。poi-ooxml-3.6.jar xmlbeans-2.3.0.jar等,如图:
2、编写相关的读写类
/**
* 读取xls文件内容
*/
private
ListXlsDto readXls() throws
IOException {
InputStream is = new
FileInputStream("test.xls");
HSSFWorkbook hssfWorkbook = new
HSSFWorkbook(is);
XlsDto xlsDto = null;
ListXlsDto list = new
ArrayListXlsDto();
// 循环工作表Sheet
for
(int numSheet = 0; numSheet hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if
(hssfSheet == null) {
continue;
}
// 循环行Row
for
(int rowNum = 1; rowNum = hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if
(hssfRow == null) {
continue;
}
xlsDto = new
XlsDto();
// 循环列Cell
// 0学号 1姓名 2学院 3课程名 4 成绩
// for (int cellNum = 0; cellNum =4; cellNum++) {
HSSFCell xh = hssfRow.getCell(0);
if
(xh == null) {
continue;
}
xlsDto.setXh(getValue(xh));
HSSFCell xm = hssfRow.getCell(1);
if
(xm == null) {
continue;
}
xlsDto.setXm(getValue(xm));
HSSFCell yxsmc = hssfRow.getCell(2);
if
(yxsmc == null) {
continue;
}
xlsDto.setYxsmc(getValue(yxsmc));
HSSFCell kcm = hssfRow.getCell(3);
if
(kcm == null) {
continue;
}
xlsDto.setKcm(getValue(kcm));
HSSFCell cj = hssfRow.getCell(4);
if
(cj == null) {
continue;
}
xlsDto.setCj(Float.parseFloat(getValue(cj)));
list.add(xlsDto);
}
}
return
list;
}
3、导出就是输入到一个新的excel文件里面
public void writeXls(ListStudent list, String path) throws Exception {
if (list == null) {原始数据为空,直接返回
return;
}
int countColumnNum = list.size();//设置列数
HSSFWorkbook book = new HSSFWorkbook(); //创建工作表对象
HSSFSheet sheet = book.createSheet("studentSheet");
// 创建第一行
HSSFRow firstRow = sheet.createRow(0);
HSSFCell[] firstCells = new HSSFCell[countColumnNum];
//创建表头
String[] options = { "no", "name", "age", "score" };
//循环数据域
for (int j = 0; j options.length; j++) {
firstCells[j] = firstRow.createCell(j);
firstCells[j].setCellValue(new HSSFRichTextString(options[j]));
}
//处理每一个cell的值
for (int i = 0; i countColumnNum; i++) {
HSSFRow row = sheet.createRow(i + 1);
Student student = list.get(i);
for (int column = 0; column options.length; column++) {
HSSFCell no = row.createCell(0);
HSSFCell name = row.createCell(1);
HSSFCell age = row.createCell(2);
HSSFCell score = row.createCell(3);
no.setCellValue(student.getNo());
name.setCellValue(student.getName());
age.setCellValue(student.getAge());
score.setCellValue(student.getScore());
}
}
File file = new File(path);
OutputStream os = new FileOutputStream(file);
System.out.println(Common.WRITE_DATA + path);
book.write(os);
os.close();
}
如何用java实现mysql数据库的导入导出
要使用CMD命令窗口首先的将MYSQL环境变量设置到操作系统中,这是第一步,
导出MYSQL数据的命令如下:
mysqldump -u root [-p password] database [table] x.sql
注:root的登录数据库的用户名;database为使用到的数据库;table为表名;x.sql为导出的sql脚本
这样导出为一个SQL脚本文件,里面包括所有的建表语句与数据插入语句,
而数据导入也差不多,给传入一个SQL脚本,语句如下:
source d:/mysql.sql;