内容导航:


一、如何从java输出到excel


用JAVA程序,读取或者写入excel文件,通过用jxl或者poi,下面是我给你写的例子。分别是用jxl读写excel文件,用poi读写excel文件。希望对你有帮助。(需要下载jxl和poi的jar包)

package util.excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.poifs.filesystem.POIFSFileSystem;

public class ExcelUtil {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String outFile = "D:/workspace/JavaStudy/src/util/excel/test.xls";
ExcelUtil.writeExcelByJXL(outFile, null);
}

/**
*
* @title: readExcelByJXL
* @description: 通过jxl读取excel文件
* @author yu ren tian
* @email yurentian@163.com
* @param excelFile
* @return
* @throws IOException
*/
private static List readExcelByJXL(String excelFile) throws IOException {
List rtn = new ArrayList();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(excelFile);
Workbook excelWorkBook = Workbook.getWorkbook(fileInputStream);
Sheet sheet = excelWorkBook.getSheet(0);
int m = sheet.getRows();
int n = sheet.getColumns();
for (int i = 1; i < m; i++) {
Map map = new HashMap();
for (int j = 0; j < n; j++) {
Cell cell = sheet.getCell(j, i);
String cellContent = cell.getContents();
switch (j) {
case 0:
map.put("studentName", cellContent);
break;
case 1:
map.put("Chinese", cellContent);
break;
case 2:
map.put("Math", cellContent);
break;
case 3:
map.put("English", cellContent);
break;
case 4:
map.put("assess", cellContent);
break;
}
}
rtn.add(map);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != fileInputStream) {
fileInputStream.close();
}
return rtn;
}
}

/**
*
* @title: writeExcelByJXL
* @description: 通过jxl写入excel文件
* @author yu ren tian
* @email yurentian@163.com
* @param outFile
* @param list
* @throws IOException
*/
private static void writeExcelByJXL(String outFile, List list)
throws IOException {
WritableWorkbook wwb;
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
// wwb = Workbook.createWorkbook(file);
wwb = Workbook.createWorkbook(fos);
WritableSheet sheet = wwb.createSheet("test", 0);
// 设置单元格的文字格式
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
Colour.BLUE);
WritableCellFormat wcf = new WritableCellFormat(wf);
//wcf.setBackground(Colour.GREEN);
wcf.setBackground(new CustomColor(11, "", 0, 0, 0));
for (int i = 0; i < 10; i++) {
Label label = new Label(i, 0, i + "", wcf);
sheet.addCell(label);
}

wwb.write();
wwb.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
*
* @title: readExcelByPOI
* @description: 通过poi读取excel文件
* @author yu ren tian
* @email yurentian@163.com
* @param excelFile
* @return
* @throws IOException
*/
private static List readExcelByPOI(String excelFile) throws IOException {
List rtn = new ArrayList();
FileInputStream fin = null;
try {
fin = new FileInputStream(excelFile);
POIFSFileSystem fs = new POIFSFileSystem(fin);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
int m = sheet.getLastRowNum() - sheet.getFirstRowNum() + 1;
int n = 5;
for (int i = 1; i < m; i++) {
Map map = new HashMap();
for (int j = 0; j < n; j++) {
HSSFCell cell = sheet.getRow(i).getCell((short) j);
int type = cell.getCellType();
String cellContentString = null;
double cellContentDouble = 0;
if (type == 1) {
cellContentString = cell.getRichStringCellValue()
.getString();
System.out.println("cellContentString="
+ cellContentString);
} else if (type == 0) {
cellContentDouble = cell.getNumericCellValue();
System.out.println("cellContentDouble="
+ cellContentDouble);
}
System.out.println("j=" + j);
switch (j) {
case 0:
map.put("studentName", cellContentString);
break;
case 1:
map.put("Chinese", new Double(cellContentDouble));
break;
case 2:
map.put("Math", new Double(cellContentDouble));
break;
case 3:
map.put("English", new Double(cellContentDouble));
break;
case 4:
map.put("assess", cellContentString);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null) {
fin.close();
}
return rtn;
}
}

/**
*
* @title: writeExcelByPOI
* @description: 通过poi写入excel
* @author yu ren tian
* @email yurentian@163.com
* @param outFile
* @param list
* @throws IOException
*/
private static void writeExcelByPOI(String outFile, List list)
throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
HSSFWorkbook wb = new HSSFWorkbook();
for (int sheetCount = 0; sheetCount < 5; sheetCount++) {
HSSFSheet sheet = wb.createSheet("组织" + (sheetCount + 1));
for (int rowCount = 0; rowCount < 10; rowCount++) {
for (int columnCount = 0; columnCount < 10; columnCount++) {
HSSFRow row = sheet.createRow(rowCount);
HSSFCell cell = row.createCell(new Short(columnCount + ""));
HSSFRichTextString richTextString = new HSSFRichTextString(
"行=" + rowCount + " 列=" + columnCount);
cell.setCellValue(richTextString);
}
}
}
wb.write(fos);
}
}


二、如何用java把数据写入到excel


需要导入jxl.jar
搭建环境
将下载后的文件解包,得到jxl.jar,放入classpath,安装就完成了。

创建文件
拟生成一个名为“测试数据.xls”的Excel文件,其中第一个工作表被命名为“第一页”,大致效果如下:
代码(CreateXLS.java):
//生成Excel的类
import java.io.*;
import jxl.*;
import jxl.write.*;
public class CreateXLS
{
public static void main(String args[])
{
try
{
//打开文件
WritableWorkbook book=
Workbook.createWorkbook(new File(“测试.xls”));
//生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet=book.createSheet(“第一页”,0);
//在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
//以及单元格内容为test
Label label=new Label(0,0,”test”);
//将定义好的单元格添加到工作表中
sheet.addCell(label);
/*生成一个保存数字的单元格
必须使用Number的完整包路径,否则有语法歧义
单元格位置是第二列,第一行,值为789.123*/
jxl.write.Number number = new jxl.write.Number(1,0,789.123);
sheet.addCell(number);
//写入数据并关闭文件
book.write();
book.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
编译执行后,会在当前位置产生一个Excel文件。


三、如何在java程序中导入excel数据


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;

public class ReadExcel2 {

/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File("src/test.xls");

String[][] data = getData(file, 0);
printStringArray(data);

}

public static void printStringArray(String[][] data){
for(int i =0; i< data.length; i++){
for(int j=0; j< data[i].length; j++){
System.out.print(data[i][j]+"t");
}
System.out.print("n");
}
}

/**
*
* 读取Excel的内容,第一维数组存储的是一行中格列的值,二维数组存储的是多少个行
* @param file 读取数据的源Excel
* @param ignoreRows 读取数据忽略的行数,比喻行头不需要读入 忽略的行数为1
* @return 读出的Excel中数据的内容
* @throws FileNotFoundException
* @throws IOException
*/

public static String[][] getData(File file, int ignoreRows)

throws FileNotFoundException, IOException {

List result = new ArrayList();

int rowSize = 0;

BufferedInputStream in = new BufferedInputStream(new FileInputStream(
file));

// 打开HSSFWorkbook
POIFSFileSystem fs = new POIFSFileSystem(in);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFCell cell = null;

for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {

HSSFSheet st = wb.getSheetAt(sheetIndex);

// 第一行为标题,不取
for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
HSSFRow row = st.getRow(rowIndex);
if (row == null) {
continue;
}
int tempRowSize = row.getLastCellNum() + 1;
if (tempRowSize > rowSize) {
rowSize = tempRowSize;
}

String[] values = new String[rowSize];
Arrays.fill(values, "");
boolean hasValue = false;

for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {

String value = "";
cell = row.getCell(columnIndex);
if (cell != null) {
// 注意:一定要设成这个,否则可能会出现乱码
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;

case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd")
.format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell
.getNumericCellValue());
}
break;

case HSSFCell.CELL_TYPE_FORMULA:
// 导入时如果为公式生成的数据则无值
if (!cell.getStringCellValue().equals("")) {
value = cell.getStringCellValue();
} else {
value = cell.getNumericCellValue() + "";
}

break;

case HSSFCell.CELL_TYPE_BLANK:
break;

case HSSFCell.CELL_TYPE_ERROR:
value = "";
break;

case HSSFCell.CELL_TYPE_BOOLEAN:
value = (cell.getBooleanCellValue() == true ? "Y"
: "N");
break;

default:
value = "";
}
}

if (columnIndex == 0 && value.trim().equals("")) {
break;
}

values[columnIndex] = rightTrim(value);
hasValue = true;
}

if (hasValue) {
result.add(values);
}
}
}

in.close();

String[][] returnArray = new String[result.size()][rowSize];

for (int i = 0; i < returnArray.length; i++) {
returnArray[i] = (String[]) result.get(i);
}

return returnArray;
}

/**
*
* 去掉字符串右边的空格
* @param str 要处理的字符串
* @return 处理后的字符串
*/

public static String rightTrim(String str) {
if (str == null) {
return "";
}
int length = str.length();
for (int i = length - 1; i >= 0; i--) {
if (str.charAt(i) != 0x20) {
break;
}
length--;
}
return str.substring(0, length);

}

}