新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

java生成表格代码 java 生成excel表格

java如何输出xls格式的Excel表格文件

有个开源的东东-jxl.jar,可以到下载。

济源ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!

一.读取Excel文件内容

/**读取Excel文件的内容

* @param file 待读取的文件

* @return

*/

public static String readExcel(File file){

StringBuffer sb = new StringBuffer();

Workbook wb = null;

try {

//构造Workbook(工作薄)对象

wb=Workbook.getWorkbook(file);

} catch (BiffException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

if(wb==null)

return null;

//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了

Sheet[] sheet = wb.getSheets();

if(sheet!=nullsheet.length0){

//对每个工作表进行循环

for(int i=0;isheet.length;i++){

//得到当前工作表的行数

int rowNum = sheet[i].getRows();

for(int j=0;jrowNum;j++){

//得到当前行的所有单元格

Cell[] cells = sheet[i].getRow(j);

if(cells!=nullcells.length0){

//对每个单元格进行循环

for(int k=0;kcells.length;k++){

//读取当前单元格的值

String cellValue = cells[k].getContents();

sb.append(cellValue+" ");

}

}

sb.append(" ");

}

sb.append(" ");

}

}

//最后关闭资源,释放内存

wb.close();

return sb.toString();

}

二.写入Excel文件

这里有很多格式了,比如文本内容加粗,加上某些颜色等,可以参考jxl的api,同时还推荐一篇不错的文章:

/**生成一个Excel文件

* @param fileName 要生成的Excel文件名

*/

public static void writeExcel(String fileName){

WritableWorkbook wwb = null;

try {

//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象

wwb = Workbook.createWorkbook(new File(fileName));

} catch (IOException e) {

e.printStackTrace();

}

if(wwb!=null){

//创建一个可写入的工作表

//Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置

WritableSheet ws = wwb.createSheet("sheet1", 0);

//下面开始添加单元格

for(int i=0;i10;i++){

for(int j=0;j5;j++){

//这里需要注意的是,在Excel中,第一个参数表示列,第二个表示行

Label labelC = new Label(j, i, "这是第"+(i+1)+"行,第"+(j+1)+"列");

try {

//将生成的单元格添加到工作表中

ws.addCell(labelC);

} catch (RowsExceededException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

}

}

try {

//从内存中写入文件中

wwb.write();

//关闭资源,释放内存

wwb.close();

} catch (IOException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

}

}

三.在一个Excel文件中查找是否包含某一个关键字

/**搜索某一个文件中是否包含某个关键字

* @param file 待搜索的文件

* @param keyWord 要搜索的关键字

* @return

*/

public static boolean searchKeyWord(File file,String keyWord){

boolean res = false;

Workbook wb = null;

try {

//构造Workbook(工作薄)对象

wb=Workbook.getWorkbook(file);

} catch (BiffException e) {

return res;

} catch (IOException e) {

return res;

}

if(wb==null)

return res;

//获得了Workbook对象之后,就可以通过它得到Sheet(工作表)对象了

Sheet[] sheet = wb.getSheets();

boolean breakSheet = false;

if(sheet!=nullsheet.length0){

//对每个工作表进行循环

for(int i=0;isheet.length;i++){

if(breakSheet)

break;

//得到当前工作表的行数

int rowNum = sheet[i].getRows();

boolean breakRow = false;

for(int j=0;jrowNum;j++){

if(breakRow)

break;

//得到当前行的所有单元格

Cell[] cells = sheet[i].getRow(j);

if(cells!=nullcells.length0){

boolean breakCell = false;

//对每个单元格进行循环

for(int k=0;kcells.length;k++){

if(breakCell)

break;

//读取当前单元格的值

String cellValue = cells[k].getContents();

if(cellValue==null)

continue;

if(cellValue.contains(keyWord)){

res = true;

breakCell = true;

breakRow = true;

breakSheet = true;

}

}

}

}

}

}

//最后关闭资源,释放内存

wb.close();

return res;

}

四.往Excel中插入图片图标

插入图片的实现很容易,参看以下代码:

/**往Excel中插入图片

* @param dataSheet 待插入的工作表

* @param col 图片从该列开始

* @param row 图片从该行开始

* @param width 图片所占的列数

* @param height 图片所占的行数

* @param imgFile 要插入的图片文件

*/

public static void insertImg(WritableSheet dataSheet, int col, int row, int width,

int height, File imgFile){

WritableImage img = new WritableImage(col, row, width, height, imgFile);

dataSheet.addImage(img);

}

以上代码的注释已经很清楚了,大概也就不用再解释了,我们可以用如下程序验证:

try {

//创建一个工作薄

WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));

//待插入的工作表

WritableSheet imgSheet = workbook.createSheet("Images",0);

//要插入的图片文件

File imgFile = new File("D:/1.png");

//图片插入到第二行第一个单元格,长宽各占六个单元格

insertImg(imgSheet,0,1,6,6,imgFile);

workbook.write();

workbook.close();

} catch (IOException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

但是jxl只支持png格式的图片,jpg格式和gif格式都不支持

五.插入页眉页脚

一般的页眉页脚都分为三个部分,左,中,右三部分,利用如下代码可实现插入页眉页脚

/**向Excel中加入页眉页脚

* @param dataSheet 待加入页眉的工作表

* @param left

* @param center

* @param right

*/

public static void setHeader(WritableSheet dataSheet,String left,String center,String right){

HeaderFooter hf = new HeaderFooter();

hf.getLeft().append(left);

hf.getCentre().append(center);

hf.getRight().append(right);

//加入页眉

dataSheet.getSettings().setHeader(hf);

//加入页脚

//dataSheet.getSettings().setFooter(hf);

}

我们可以用如下代码测试该方法:

try {

//创建一个工作薄

WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));

//待插入的工作表

WritableSheet dataSheet = workbook.createSheet("加入页眉",0);

ExcelUtils.setHeader(dataSheet, "chb", "2007-03-06", "第1页,共3页");

workbook.write();

workbook.close();

} catch (IOException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

六偷懒工具设计之sql2Excel

今天在公司陪山东客户调试,远程登录,我在linux下什么工具都没有,用ssh登录服务器,直接用mysql查询数据库,提出记录中的所有汉字全是乱码。哎,可恶的公司,不让我用windows,要不我就可以用putty或者EMS了,我ft!

甚是不爽之下,我决定自己写个工具了,把客户数据库中的数据全部提取并保存到Excel中,这样我不就可以一目了然了嘛,嘿嘿,好吧,那我就写一个工具吧。

第一部分就是谁都会的jdbc操作,连接数据库,提取数据集合。

Connection con;

Statement state;

/**初始化连接

* @param serverIp

* @param dataBase

* @param userName

* @param password

* @throws ClassNotFoundException

* @throws SQLException

*/

public void init(String serverIp,String dataBase,String userName,String password) throws ClassNotFoundException, SQLException{

Class.forName("com.mysql.jdbc.Driver");

//配置数据源

String url="jdbc:mysql://"+serverIp+"/"+dataBase+"?useUnicode=truecharacterEncoding=GB2312";

con=DriverManager.getConnection(url,userName,password);

}

/**得到查询结果集

* @param sql

* @return

* @throws SQLException

*/

public ResultSet getResultSet(String sql) throws SQLException{

state = con.createStatement();

ResultSet res = state.executeQuery(sql);

return res;

}

/**关闭连接

* @throws SQLException

*/

public void close() throws SQLException{

if(con!=null)

con.close();

if(state!=null)

state.close();

}

第二部分就是把ResultSet中的记录写入一个Excel文件

操作Excel,我用的是jxl,不熟的同学可以参考:利用java操作Excel文件

/**将查询结果写入Excel文件中

* @param rs

* @param file

* @throws SQLException

*/

public void writeExcel(ResultSet rs,File file) throws SQLException{

WritableWorkbook wwb = null;

try{

//首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象

wwb = Workbook.createWorkbook(file);

} catch (IOException e){

e.printStackTrace();

}

if(wwb!=null){

WritableSheet ws = wwb.createSheet("sheet1", 0);

int i=0;

while(rs.next()){

Label label1 = new Label(0, i, rs.getString("id"));

Label label2 = new Label(1, i, rs.getString("category"));

try {

ws.addCell(label1);

ws.addCell(label2);

} catch (RowsExceededException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

i++;

}

try {

//从内存中写入文件中

wwb.write();

//关闭资源,释放内存

wwb.close();

} catch (IOException e) {

e.printStackTrace();

} catch (WriteException e){

e.printStackTrace();

}

}

}

测试程序:

Sql2Excel se = new Sql2Excel();

try {

se.init("127.0.0.1","mydabase", "root", "1234");

ResultSet rs = se.getResultSet("select id,category from xx ");

se.writeExcel(rs, new File("/root/sql2excel.xls"));

se.close();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

java 生成PDF表格

实现代码如下:

package com.qhdstar.java.pdf;

import java.awt.Color;

import java.io.FileOutputStream;

import com.lowagie.text.Chapter;

import com.lowagie.text.Document;

import com.lowagie.text.Font;

import com.lowagie.text.FontFactory;

import com.lowagie.text.PageSize;

import com.lowagie.text.Paragraph;

import com.lowagie.text.Section;

import com.lowagie.text.pdf.PdfWriter;

/**

* 描述:TODO 【JAVA生成PDF】

*

*

* @title GeneratePDF

* @version V1.0

*/

public class GeneratePDF {

public static void main(String[] args) {

//调用第一个方法,向C盘生成一个名字为ITextTest.pdf 的文件

try {

writeSimplePdf();

}

catch (Exception e) { e.printStackTrace(); }

//调用第二个方法,向C盘名字为ITextTest.pdf的文件,添加章节。

try {

writeCharpter();

}

catch (Exception e) { e.printStackTrace(); }

}

public static void writeSimplePdf() throws Exception {

// 1.新建document对象

// 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。

Document document = new Document(PageSize.A4, 50, 50, 50, 50);

// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。

// 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));

// 3.打开文档

document.open();

// 4.向文档中添加内容

// 通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("Some more text on the first page with different color and font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new Color(255, 150, 200))));

// 5.关闭文档

document.close();

}

/**

* 添加含有章节的pdf文件

*

* @throws Exception

*/

public static void writeCharpter() throws Exception {

// 新建document对象 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。

Document document = new Document(PageSize.A4, 20, 20, 20, 20);

// 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:\\ITextTest.pdf"));

// 打开文件

document.open();

// 标题

document.addTitle("Hello mingri example");

// 作者

document.addAuthor("wolf");

// 主题

document.addSubject("This example explains how to add metadata.");

document.addKeywords("iText, Hello mingri");

document.addCreator("My program using iText");

// document.newPage();

// 向文档中添加内容

document.add(new Paragraph("\n"));

document.add(new Paragraph("\n"));

document.add(new Paragraph("\n"));

document.add(new Paragraph("\n"));

document.add(new Paragraph("\n"));

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("First page of the document."));

document.add(new Paragraph("Some more text on the first page with different color and font type.", FontFactory.getFont(FontFactory.defaultEncoding, 10, Font.BOLD, new Color(0, 0, 0))));

Paragraph title1 = new Paragraph("Chapter 1", FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));

// 新建章节

Chapter chapter1 = new Chapter(title1, 1);

chapter1.setNumberDepth(0);

Paragraph title11 = new Paragraph("This is Section 1 in Chapter 1", FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));

Section section1 = chapter1.addSection(title11);

Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");

section1.add(someSectionText);

someSectionText = new Paragraph("Following is a 3 X 2 table.");

section1.add(someSectionText);

document.add(chapter1);

// 关闭文档

document.close();

}

}

java中输入输出流如何把数据输出为Excel表格形式

实现代码如下:

import org.apache.poi.hssf.usermodel.*;

import java.io.FileOutputStream;

import java.io.IOException;

publicclass CreateCells

{

publicstaticvoid main(String[] args)

throws IOException

{

HSSFWorkbook wb = new HSSFWorkbook();//建立新HSSFWorkbook对象

HSSFSheet sheet = wb.createSheet("new sheet");//建立新的sheet对象

// Create a row and put some cells in it. Rows are 0 based.

HSSFRow row = sheet.createRow((short)0);//建立新行

// Create a cell and put a value in it.

HSSFCell cell = row.createCell((short)0);//建立新cell

cell.setCellValue(1);//设置cell的整数类型的值

// Or do it on one line.

row.createCell((short)1).setCellValue(1.2);//设置cell浮点类型的值

row.createCell((short)2).setCellValue("test");//设置cell字符类型的值

row.createCell((short)3).setCellValue(true);//设置cell布尔类型的值

HSSFCellStyle cellStyle = wb.createCellStyle();//建立新的cell样式

cellStyle.setDataFormat(HSSFDataFormat.getFormat("m/d/yy h:mm"));//设置cell样式为定制的日期格式

HSSFCell dCell =row.createCell((short)4);

dCell.setCellValue(new Date());//设置cell为日期类型的值

dCell.setCellStyle(cellStyle); //设置该cell日期的显示格式

HSSFCell csCell =row.createCell((short)5);

csCell.setEncoding(HSSFCell.ENCODING_UTF_16);//设置cell编码解决中文高位字节截断

csCell.setCellValue("中文测试_Chinese Words Test");//设置中西文结合字符串

row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);//建立错误cell

// Write the output to a file

FileOutputStream fileOut = new FileOutputStream("workbook.xls");

wb.write(fileOut);

fileOut.close();

}

}

Java是由Sun Microsystems公司推出的Java面向对象程序设计语言(以下简称Java语言)和Java平台的总称。由James Gosling和同事们共同研发,并在1995年正式推出。Java最初被称为Oak,是1991年为消费类电子产品的嵌入式芯片而设计的。1995年更名为Java,并重新设计用于开发Internet应用程序。

用Java实现的HotJava浏览器(支持Java applet)显示了Java的魅力:跨平台、动态Web、Internet计算。从此,Java被广泛接受并推动了Web的迅速发展,常用的浏览器均支持Javaapplet。另一方面,Java技术也不断更新。Java自面世后就非常流行,发展迅速,对C++语言形成有力冲击。在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。2010年Oracle公司收购Sun Microsystems。

用java编写一个创建数据库和表的程序的代码怎么写

import java.sql.*;

public class Test

{

public static void main(String[] args) throws Exception

{

Class.forName("com.mysql.jdbc.Driver");

//一开始必须填一个已经存在的数据库

String url = "jdbc:mysql://localhost:3306/test?useUnicode=truecharacterEncoding=utf-8";    

Connection conn = DriverManager.getConnection(url, "root", "123456");

Statement stat = conn.createStatement();

//创建数据库hello

stat.executeUpdate("create database hello");

//打开创建的数据库

stat.close();

conn.close();

url = "jdbc:mysql://localhost:3306/hello?useUnicode=truecharacterEncoding=utf-8";

conn = DriverManager.getConnection(url, "root", "123456");

stat = conn.createStatement();

//创建表test

stat.executeUpdate("create table test(id int, name varchar(80))");

//添加数据

stat.executeUpdate("insert into test values(1, '张三')");

stat.executeUpdate("insert into test values(2, '李四')");

//查询数据

ResultSet result = stat.executeQuery("select * from test");

while (result.next())

{

System.out.println(result.getInt("id") + " " + result.getString("name"));

}

//关闭数据库

result.close();

stat.close();

conn.close();

}

}


文章名称:java生成表格代码 java 生成excel表格
网页路径:http://www.wjwzjz.com/article/ddsosej.html
在线咨询
服务热线
服务热线:028-86922220
TOP