public class JxlExcel {
public static void main(String[] args) {
//创建Excel文件
String[] title= {"姓名","课程名","分数"};
File file=new File("f:/sheet1.xls");
try {
file.createNewFile();
//创建工作簿
WritableWorkbook workbook=Workbook.createWorkbook(file);
//创建Sheet
WritableSheet sheet=workbook.createSheet("表格一", 20);
//第一行设置列名
Label label=null;
for (int i = 0; i < title.length; i++) {
label=new Label(i, 0, title[i]);//第一个参数为列,第二个为行
sheet.addCell(label);
}
Data data=new Data();
ResultSet rs=data.getString();
while(rs.next()) {
System.out.println(rs.getString(1));
label=new Label(0,rs.getRow(),rs.getString(1));
sheet.addCell(label);
label=new Label(1,rs.getRow(),rs.getString(2));
sheet.addCell(label);
label=new Label(2,rs.getRow(),rs.getString(3));
sheet.addCell(label);
}
workbook.write();
workbook.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} } 2,从Excel表格中读取数据
public class JxlRead {
public static void main(String[] args) {
//创建workbook
try {
Workbook workbook=Workbook.getWorkbook(new File("f:/sheet1.xls"));
//获取第一个表格
Sheet sheet=workbook.getSheet(0);
//获取数据
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell=sheet.getCell(j, i);
System.out.print(cell.getContents()+" ");
}
System.out.println();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} 三.Poi读写基础代码
//所需jar包:commons-io-2.2.jar;poi-3.11-20141221.jar
//通过poi进行excel导入数据
public class PoiExcel {
public static void main(String[] args) throws SQLException {
String title[]= {"名字","课程","分数"};
//1.创建Excel工作簿
HSSFWorkbook workbook=new HSSFWorkbook();
//2.创建一个工作表
HSSFSheet sheet=workbook.createSheet("sheet2");
//3.创建第一行
HSSFRow row=sheet.createRow(0);
HSSFCell cell=null;
//4.插入第一行数据
for (int i = 0; i < title.length; i++) {
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
//5.追加数据
Data data=new Data();
ResultSet rs=data.getString();
while(rs.next()) {
HSSFRow row2=sheet.createRow(rs.getRow());
HSSFCell cell2=row2.createCell(0);
cell2.setCellValue(rs.getString(1));
cell2=row2.createCell(1);
cell2.setCellValue(rs.getString(2));
cell2=row2.createCell(2);
cell2.setCellValue(rs.getString(3));
}
//创建一个文件,将Excel内容存盘
File file=new File("e:/sheet2.xls");
try {
file.createNewFile();
FileOutputStream stream=FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} //将Excel表中内容读取
public class PoiRead {
public static void main(String[] args) {
//需要解析的Excel文件
File file=new File("e:/sheet2.xls");
try {
//获取工作簿
FileInputStream fs=FileUtils.openInputStream(file);
HSSFWorkbook workbook=new HSSFWorkbook(fs);
//获取第一个工作表
HSSFSheet hs=workbook.getSheetAt(0);
//获取Sheet的第一个行号和最后一个行号
int last=hs.getLastRowNum();
int first=hs.getFirstRowNum();
//遍历获取单元格里的信息
for (int i = first; i <last; i++) {
HSSFRow row=hs.getRow(i);
int firstCellNum=row.getFirstCellNum();//获取所在行的第一个行号
int lastCellNum=row.getLastCellNum();//获取所在行的最后一个行号
for (int j = firstCellNum; j <lastCellNum; j++) {
HSSFCell cell=row.getCell(j);
String value=cell.getStringCellValue();
System.out.print(value+" ");
}
System.out.println();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} 如果Excel版本过高则需要改写用XSSF
public class PoiExpExcel2 { /**
* POI生成Excel文件
* @author David
* @param args
*/
public static void main(String[] args) { String[] title = {"id","name","sex"}; //创建Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//创建一个工作表sheet
Sheet sheet = workbook.createSheet();
//创建第一行
Row row = sheet.createRow(0);
Cell cell = null;
//插入第一行数据 id,name,sex
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//追加数据
for (int i = 1; i <= 10; i++) {
Row nextrow = sheet.createRow(i);
Cell cell2 = nextrow.createCell(0);
cell2.setCellValue("a" + i);
cell2 = nextrow.createCell(1);
cell2.setCellValue("user" + i);
cell2 = nextrow.createCell(2);
cell2.setCellValue("男");
}
//创建一个文件
File file = new File("e:/poi_test.xlsx");
try {
file.createNewFile();
//将Excel内容存盘
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
} } } 四.定制导入模板
1.首先准备好模板的.xml文件,然后导入所需的jar包
例子:student.xml文件 <?xml version="1.0" encoding="UTF-8"?>
<excel id="student" code="student" name="学生信息导入">
<colgroup>
<col index="A" width='17em'></col>
<col index="B" width='17em'></col>
<col index="C" width='17em'></col>
<col index="D" width='17em'></col>
<col index="E" width='17em'></col>
<col index="F" width='17em'></col>
</colgroup>
<title>
<tr height="16px">
<td rowspan="1" colspan="6" value="学生信息导入" />
</tr>
</title>
<thead>
<tr height="16px">
<th value="编号" />
<th value="姓名" />
<th value="年龄" />
<th value="性别" />
<th value="出生日期" />
<th value=" 爱好" />
</tr>
</thead>
<tbody>
<tr height="16px" firstrow="2" firstcol="0" repeat="5">
<td type="string" isnullable="false" maxlength="30" /><!--用户编号 -->
<td type="string" isnullable="false" maxlength="50" /><!--姓名 -->
<td type="numeric" format="##0" isnullable="false" /><!--年龄 -->
<td type="enum" format="男,女" isnullable="true" /><!--性别 -->
<td type="date" isnullable="false" maxlength="30" /><!--出生日期 -->
<td type="enum" format="足球,篮球,乒乓球" isnullable="true" /><!--爱好 -->
</tr>
</tbody>
</excel> 所需jar包:
commons-lang3-3.1.jar
jdom.jar
poi-3.11-20141221.jar
commons-io-2.2.jar java代码:
//准备工作:导入相关jar包commons-lang3-3.1.jar,jdom.jar,poi-3.11-20141221.jar
public class CreateTemp {
public static void main(String[] args) {
//获取解析Xml路径
String path=System.getProperty("user.dir")+"/student.xml";
File file=new File(path);
SAXBuilder builder=new SAXBuilder();
//解析xml文件
try {
Document document=builder.build(file);
//创建Excel
HSSFWorkbook workbook=new HSSFWorkbook();
//创建表格
HSSFSheet sheet=workbook.createSheet("sheet0");
//获取Xml文件的根节点
Element root=document.getRootElement();
//获取模板名称
String tempName=root.getAttributeValue("name");
//设置列宽
Element colgroup=root.getChild("colgroup");
setColumnWidth(sheet,colgroup);
//设置标题
int rownum = 0;
int column = 0;
Element title=root.getChild("title");
List<Element> trs=title.getChildren("tr");
for (int i = 0; i <trs.size(); i++) {
Element tr=trs.get(i);
List<Element> tds=tr.getChildren("td");
HSSFRow row=sheet.createRow(rownum);
HSSFCellStyle cellStyle=workbook.createCellStyle();//创建单元格格式
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//标题居中
for (int j = 0; j < tds.size(); j++) {
Element td=tds.get(j);
HSSFCell cell=row.createCell(j);
Attribute rowspan=td.getAttribute("rowspan");
Attribute colspan=td.getAttribute("colspan");
Attribute value=td.getAttribute("value");
if (value!=null) {
String content=value.getValue(); cell.setCellValue(content);
int rspan=rowspan.getIntValue()-1;
int cspan=colspan.getIntValue()-1;
//设置字体
HSSFFont font=workbook.createFont();
font.setFontName("仿宋_GB2312");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//字体加粗
// font.setFontHeight((short)12);
font.setFontHeightInPoints((short)12);
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
//合并单元格居中
sheet.addMergedRegion(new CellRangeAddress(rspan, rspan, 0, cspan));
} }
rownum++; }
//设置表头
Element thead=root.getChild("thead");
trs=thead.getChildren("tr");
for (int i = 0; i < trs.size(); i++) {
Element tr=trs.get(i);
HSSFRow row=sheet.createRow(rownum);
List<Element> ths=tr.getChildren("th");
for (int j = 0; j <ths.size(); j++) {
Element th=ths.get(j);
HSSFCell cell=row.createCell(j);
Attribute value=th.getAttribute("value");
if (value!=null) {
String content=value.getValue();
cell.setCellValue(content); }
}
rownum++;
} //设置数据区域样式
Element tbody = root.getChild("tbody");
Element tr=tbody.getChild("tr");
int repeat=tr.getAttribute("repeat").getIntValue();
List<Element> tds=tr.getChildren("td");
for (int i = 0; i < repeat; i++) {
HSSFRow row=sheet.createRow(rownum);
for (int j = 0; j < tds.size(); j++) {
Element td=tds.get(j);
HSSFCell cell=row.createCell(j);
setType(workbook,cell,td);
}
}
rownum++;
//生成Excel导入模板
File tempFile=new File("e:/"+tempName+".xls");
tempFile.delete();
tempFile.createNewFile();
FileOutputStream fos=FileUtils.openOutputStream(tempFile);
workbook.write(fos);
fos.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private static void setType(HSSFWorkbook workbook, HSSFCell cell, Element td) {
Attribute typeAttr = td.getAttribute("type");
String type = typeAttr.getValue();
HSSFDataFormat format = workbook.createDataFormat();
HSSFCellStyle cellStyle = workbook.createCellStyle();
if("NUMERIC".equalsIgnoreCase(type)){
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
Attribute formatAttr = td.getAttribute("format");
String formatValue = formatAttr.getValue();
formatValue = StringUtils.isNotBlank(formatValue)? formatValue : "#,##0.00";
cellStyle.setDataFormat(format.getFormat(formatValue));
}else if("STRING".equalsIgnoreCase(type)){
cell.setCellValue("");
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cellStyle.setDataFormat(format.getFormat("@"));
}else if("DATE".equalsIgnoreCase(type)){
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellStyle.setDataFormat(format.getFormat("yyyy-m-d"));
}else if("ENUM".equalsIgnoreCase(type)){
CellRangeAddressList regions =
new CellRangeAddressList(cell.getRowIndex(), cell.getRowIndex(),
cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format");
String enumValue = enumAttr.getValue();
//加载下拉列表内容
DVConstraint constraint =
DVConstraint.createExplicitListConstraint(enumValue.split(","));
//数据有效性对象
HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
workbook.getSheetAt(0).addValidationData(dataValidation);
}
cell.setCellStyle(cellStyle); } private static void setColumnWidth(HSSFSheet sheet, Element colgroup) {
List<Element> cols=colgroup.getChildren("col");//获取col的节点
for (int i = 0; i < cols.size(); i++) {
Element col=cols.get(i);
Attribute width=col.getAttribute("width");//获取每列中的width属性
String unit = width.getValue().replaceAll("[0-9,\\.]", "");//单位
String value = width.getValue().replaceAll(unit, "");//数值
int v=0;
if(StringUtils.isBlank(unit) || "px".endsWith(unit)){
v = Math.round(Float.parseFloat(value) * 37F);
}else if ("em".endsWith(unit)){
v = Math.round(Float.parseFloat(value) * 267.5F);
}//对单位进行判断
sheet.setColumnWidth(i, v);
} }
}

从数据库将数据导出到excel表格的更多相关文章

  1. 将数据库中数据导出为excel表格

    public class Excel { private static Logger logger = LoggerFactory.getLogger(Excel.class); /** * 导出项目 ...

  2. 将mysql数据库的数据导出做成excl表格通过邮件发送附件发给指定人

    mysql数据库的数据导出成excl表 方法一: mysql -uroot -p123456 -e “select *.* from 表 into outfile ‘文件路径.xls’into out ...

  3. 一个php将数据库的数据导出到excle表格中的小dome

    首先我们需要下载个PHPExcel,PHPExcel下载地址链接:https://pan.baidu.com/s/1nxpAc45 密码:qgct 下面来写个dome: <?php //把数据写 ...

  4. 数据导出为excel表格

    ---恢复内容开始--- 方式一: 通过request和response中携带的数据导出表格,导出的结果会将页面中展示的内容全部导出.代码如下: //调出保存框,下载页面所有内容 String fil ...

  5. asp.net数据导出到excel表格,并设置表格样式

    1.首先在项目中添加引用

  6. Python小练习_数据库表数据导出到excel

    需求:只要传入一个表名,就能把所有的数据导入出来,字段名是excel的表头 1.要动态获取到标的字段 cur.descrption能获取到表的字段 fileds = [filed[0] for fil ...

  7. Python 把数据库的数据导出到excel表

    import io,xlwt def export_excel(request): """导出数据到excel表""" list_obj = ...

  8. oracle 数据库中数据导出到excel

    确保安装了PLSQL Developer工具.连接数据库. FIle--new--SQL window 运行查询,选中要导出的数据,右键--copy to excel. 或者 运行查询后.右键--se ...

  9. 如何数据库表数据导出到excel中

    1.首先须要有一个NPOI 2.接下来上代码 private void button1_Click(object sender, EventArgs e) { //1.通过Ado.net读取数据 st ...

随机推荐

  1. 【mq读书笔记】消息到达唤醒挂起线程检查新消息

    DefaultMessageStore#start 当新消息到达CommitLog是,ReputMessageService线程负责将消息转发给ConsumeQueue,IndexFile,如果Bro ...

  2. 冲刺随笔——Day_Five

    这个作业属于哪个课程 软件工程 (福州大学至诚学院 - 计算机工程系) 这个作业要求在哪里 团队作业第五次--Alpha冲刺 这个作业的目标 团队进行Alpha冲刺 作业正文 正文 其他参考文献 无 ...

  3. Python中sort、sorted的cmp参数废弃之后使用cmp_to_key实现类似功能

    Python2.1以前的排序比较方法只提供一个cmp比较函数参数,没有__lt__等6个富比较方法, Python 2.1引入了富比较方法,Python3.4之后作废了cmp参数.相应地从Python ...

  4. PyQt(Python+Qt)学习随笔:QListView的uniformItemSizes属性

    老猿Python博文目录 专栏:使用PyQt开发图形界面Python应用 老猿Python博客地址 QListView的uniformItemSizes属性用于控制视图中所有项是否具有相同大小,只有在 ...

  5. PyCharm中怎么将非当前工程文件的目录的文件加到当前工程中

    在PyCharm已经建立工程文件的情况下,如果要将一个其他目录的文件导入到已有的工程中,唯一的方法如下: 通过File->Settings->Project->Project Str ...

  6. 关于我 About Me

    重庆某大学计算机专业大三学渣 CTF酱油选手 web安全菜鸡 SRC低危小子 精通多门语言 hello world 输出 和 windows linux单词拼写 扣扣:MjU4NTYxNDQ2NA== ...

  7. PHP代码审计分段讲解(14)

    30题利用提交数组绕过逻辑 本篇博客是PHP代码审计分段讲解系列题解的最后一篇,对于我这个懒癌患者来说,很多事情知易行难,坚持下去,继续学习和提高自己. 源码如下: <?php $role = ...

  8. Linux文件系统简介一(磁盘分区、开机过程、目录结构、文件权限、文件扩展名、目录管理)

    Linux:就是一组软件,一套操作系统=核心+系统呼叫接口层. 1.操作系统 操作系统 = 核心(内核) + 系统呼叫(接口) 操作系统其实也是一组程序,重点在于管理计算机的所有活动以及驱动系统中的所 ...

  9. 在浏览器中输入URL后,执行的全部过程。会用到哪些协议?(一次完整的HTTP请求过程)

    在浏览器中输入URL后,执行的全部过程.会用到哪些协议?(一次完整的HTTP请求过程) 整个流程如下: 域名解析 为了将消息从你的PC上传到服务器上,需要用到IP协议.ARP协议和OSPF协议. 发起 ...

  10. springboot 导出xlsx文件

    @Override public String downModelXlsFile(SxSourceReq param, HttpServletResponse response) { //设置响应编码 ...