本文參考網絡資源
本文用jxl來操作excel
jxl下載网址,可以下载到API:http:
//www.andykhan.com/jexcelapi/download.html
package com.thh;
import java.io.File;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
* 读取Excel文件的内容
*
* @param file
* 待读取的文件
* @return // 生成Excel的类
*/
public class TestExcel {
public static void main(String[] args) {
// 打开文件
try {
WritableWorkbook book = Workbook.createWorkbook(new File(
" test.xls "));
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(" 第一页 ", 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
// 以及单元格内容为test
Label label = new Label(0, 0, " test ");
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
// 写入数据并关闭文件
book.write();
book.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.thh;
//读取Excel的类
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ReadXLS {
public static void main(String args[]) {
try {
Workbook book = Workbook.getWorkbook(new File(" test.xls "));
// 获得第一个工作表对象
Sheet sheet = book.getSheet(0);
// 得到第一列第一行的单元格
Cell cell1 = sheet.getCell(0, 0);
String result = cell1.getContents();
System.out.println(result);
book.close();
} catch (Exception e) {
// System.out.println(e);
e.printStackTrace();
}
}
}
//合并单元格并在单元格中输入内容
package com.thh;
import java.io.*;
import jxl.write.*;
import jxl.*;
public class MergeCells {
public static void main(String[] args) {
try {
WritableWorkbook book = Workbook
.createWorkbook(new File("test.xls"));
WritableSheet sheet = book.createSheet("第一页", 0);
sheet.mergeCells(3, 3, 6, 6); // 合并单元格
// 设置填充内容的格式
WritableFont font = new WritableFont(WritableFont.TIMES, 30,
WritableFont.BOLD);
WritableCellFormat format = new WritableCellFormat(font);
format.setAlignment(jxl.format.Alignment.CENTRE); // 水平居中
format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); // 垂直居中
format.setBackground(jxl.format.Colour.BLUE); // 背景颜色和样式
format.setBorder(jxl.format.Border.ALL,
jxl.format.BorderLineStyle.THICK); // 边框样式
Label label = new Label(3, 3, "合并", format); // 添加内容
sheet.addCell(label);
book.write();
book.close();
}// end try
catch (Exception e) {
e.printStackTrace();
}
}
}
//在工作表中添加图片
package com.thh;
import java.io.*;
import jxl.*;
import jxl.write.*;
public class CreateImage {
public static void main(String[] args) {
try {
WritableWorkbook book = Workbook
.createWorkbook(new File("test.xls"));
WritableSheet sheet = book.createSheet("第一页", 0);
WritableImage image = new WritableImage(
3.5,
3.5,
4.3,
8.7, // 定义图片格式
new File(
"1.png"));
sheet.addImage(image); // 添加图片
book.write();
book.close();
}// end try
catch (Exception e) {
e.printStackTrace();
}
}
}