A. 如何在java中做excel表

很簡單,這有代碼:代碼裡面資料庫訪問對象自己寫,用到第三方架包:
poi-2.5-final-20040302.jar;
poi-contrib-2.5-final-20040302.jar
poi-scratchpad-2.5-final-20040302.jar
自己去網上下吧

//處理類
public class CountExcel {

/**
* 資料庫操作類,自己寫吧。。。
*/
private OperData jdbc /*自己寫*/;

/**
* 創建excel,返回excel的存放地址
*
* @param title
* 標題
* @param sql
* 查詢語句
* @param path
* excel的存放路徑(物理地址)
* @param titlename
* 報表的名字
* @return 路徑
*/
public String createExcelForAssess(String[] title, String sql, String path,
String titlename) throws Exception {
GregorianCalendar c = new GregorianCalendar();
StringBuffer excelUrl = new StringBuffer();
java.util.Date now = c.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
String strNow = format.format(now);
excelUrl.append(path).append(File.separator).append("te_").append(
strNow).append(".xls");
// excel的表頭
Vector vcCol = new Vector();
if (title == null || title.length < 1)
return "";
for (int i = 0; i < title.length; i++) {
vcCol.add(title[i]);
}
int[] align = new int[vcCol.size()];
int[] num = new int[vcCol.size()];
for (int i = 0; i < vcCol.size(); i++) {
align[i] = 2;
num[i] = 0;
}
Vector vc = getqueryrest(sql);
ExcelReport excel = new ExcelReport();
excel.setExcelFile(excelUrl.toString());
excel.setCols(vcCol.size());
excel.createCaption(titlename);
excel.createColumnCaption(vcCol);
excel.createBody(vc, align, num);
excel.createPage(5);
excel.createFile();
return excelUrl.toString();
}

/**
* 查詢結果集
*
* @param sql傳入查詢的sql語句
* @return Vector
* @throws SQLException
*/
public Vector getqueryrest(String sql) throws SQLException {
Vector vc = new Vector();
//資料庫查詢,返回的list裡面存的是數據的pojo對象
//List list = jdbc.getQueryResult(sql);
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
String[] info = (String[]) list.get(i);
for (int j = 0; j < info.length; j++) {
vc.add(info[j]);
}
}
}
return vc;
}
}

//工具類
public class ExcelReport{
/**
* EXCEL文件工作區
*/
private HSSFWorkbook wb;

/**
* EXCEL文件SHEET
*/
private HSSFSheet sheet;

/**
* EXCEL文件存放的目錄路徑
*/
private String excelFile = "";

/**
* 記錄當前行數
*/
private int rownum = 0;

/**
* 記錄總共列數
*/
private int cols = 0;

/**
* 記錄每列的寬度
*/
private int[] length;

/**
* 記錄是否已經設定欄位數
*/
private boolean flag = false;

/**
* 設置EXCEL文件存放的目錄路徑,在生成標題,列頭前設定
*/
public void setExcelFile(String excelFile){
this.excelFile = excelFile;
}

/**
* 設置EXCEL表的列數,在生成標題,列頭前設定
*/
public void setCols(int cols){
this.cols = cols;
if(flag){
if(length.length < cols){
length = getLength(length);
}
}else{
length = new int[cols];
}
flag = true;
}

/**
* 第二次設定欄位數,保存第一張表格每列的長度
*/
private int[] getLength(int[] arr){
int[] temp = new int[cols];
for(int i=0;i<arr.length;i++){
temp[i] = arr[i];
}
return temp;
}

/**
* 初始化EXCEL報表類
*/
public ExcelReport(){
wb = new HSSFWorkbook();
sheet = wb.createSheet("new sheet");
}

/**
* 生成標題
* @param caption 標題頭
*/
public void createCaption(String caption){
//生成標題行
HSSFRow row = sheet.createRow((short)rownum);
//生成標題單元格
HSSFCell cell = row.createCell((short)0);
//生成標題單元格樣式
HSSFCellStyle style = wb.createCellStyle();

//設定標題字體
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)14);
font.setFontName("新宋體");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);

//設定標題框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);

//設定對齊方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

//設置cell編碼解決中文高位位元組截斷
cell.setEncoding(HSSFCell.ENCODING_UTF_16);

//設定單元格文字合樣式
cell.setCellValue(caption);
cell.setCellStyle(style);

for(int i=1;i<cols;i++){
cell = row.createCell((short)i);
cell.setCellStyle(style);
cell.setCellValue("");
}

//設定合並的單元格
sheet.addMergedRegion(new Region(rownum,(short)0,rownum,(short)(cols-1)));

//當前行自增
rownum++;
}

/**
* 生成列頭
* @param vc 列頭內容
*/
public void createColumnCaption(Vector vc){
//生成列頭行
HSSFRow row = sheet.createRow((short)rownum);

//生成了列頭格式
HSSFCellStyle style = wb.createCellStyle();

//設定列頭字體
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋體");
font.setColor(HSSFColor.BLACK.index);
style.setFont(font);

//設定標題框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);

//設定對齊方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

//生成列頭單元格
HSSFCell cell;
for(int i=0;i<vc.size();i++){
//生成標題單元格
cell = row.createCell((short)i);
//設置cell編碼解決中文高位位元組截斷
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//設定單元格文字合樣式
if(vc.get(i) != null){
cell.setCellValue(vc.get(i).toString());
//記錄列頭的長度
if(vc.get(i).toString().getBytes().length > length[i]){
length[i] = vc.get(i).toString().getBytes().length;
}
}else{
cell.setCellValue("");
}
cell.setCellStyle(style);
}
rownum++;
}

/**
* 生成合並的列頭
* @param vc 列頭
* @param colnum 每列要合並的列數,並且所有要合並的列數之和等於總表格列數
*/
public void mergeColumnCaption(Vector vc,int[] colnum){
//生成標題行
HSSFRow row = sheet.createRow((short)rownum);

//生成標題單元格樣式
HSSFCellStyle style = wb.createCellStyle();

//設定標題字體
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋體");
font.setColor(HSSFColor.BLACK.index);
style.setFont(font);

//設定標題框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);

//設定對齊方式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

int pos = 0;
HSSFCell cell;
for(int i=0;i<vc.size();i++){
pos = pos + colnum[i];
cell = row.createCell((short)(pos-colnum[i]));
//設置cell編碼解決中文高位位元組截斷
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//設定單元格文字合樣式
cell.setCellStyle(style);
if(vc.get(i) == null){
cell.setCellValue("");
}else{
cell.setCellValue(vc.get(i).toString());
}
for(int j=1;j<colnum[i];j++){
cell = row.createCell((short)(pos-colnum[i]+j));
cell.setCellStyle(style);
cell.setCellValue("");
}
//設定合並的單元格
sheet.addMergedRegion(new Region(rownum,(short)(pos-colnum[i]),rownum,(short)(pos-1)));
}
//當前行自增
rownum++;
}

/**
* 合並行
* @param startrow 起始行
* @param endrow 終止行
* @param column 列數
*/
public void mergeRowCaption(int startrow,int endrow,int column){
sheet.addMergedRegion(new Region(startrow,(short)column,endrow,(short)column));
}

/**
* 生成表格主體
* @param vc 表格內容
* @param align 每列的對齊方式,1為左,2為中,3為右,數組長度要等於表格列數
* @param num 每列的數據類型,0為字元串,1為數字
*/
public void createBody(Vector vc,int[] align,int[] num){
int rows = vc.size() / cols;
//設定表格字體
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋體");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
HSSFRow row;
HSSFCell cell;

//設定數據格式
HSSFDataFormat df = wb.createDataFormat();

//生成了左對齊表格格式
HSSFCellStyle styleLeft = wb.createCellStyle();
styleLeft.setFont(font);
styleLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleLeft.setBottomBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleLeft.setLeftBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleLeft.setRightBorderColor(HSSFColor.BLACK.index);
styleLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleLeft.setTopBorderColor(HSSFColor.BLACK.index);
styleLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
styleLeft.setDataFormat(df.getFormat("##################.00"));

//生成居中對齊表格格式
HSSFCellStyle styleCenter = wb.createCellStyle();
styleCenter.setFont(font);
styleCenter.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleCenter.setBottomBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleCenter.setLeftBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleCenter.setRightBorderColor(HSSFColor.BLACK.index);
styleCenter.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleCenter.setTopBorderColor(HSSFColor.BLACK.index);
styleCenter.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);
styleCenter.setDataFormat(df.getFormat("##################.00"));

//生成右對齊表格格式
HSSFCellStyle styleRight = wb.createCellStyle();
styleRight.setFont(font);
styleRight.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleRight.setBottomBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleRight.setLeftBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleRight.setRightBorderColor(HSSFColor.BLACK.index);
styleRight.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleRight.setTopBorderColor(HSSFColor.BLACK.index);
styleRight.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
styleRight.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
styleRight.setDataFormat(df.getFormat("##################.00"));

for (int i = 0;i < rows; i++){
// 創建新行
row = sheet.createRow((short)(rownum));
for (int j = 0;j < cols; j++){
// 創建一個單元格
cell = row.createCell((short)j);
//設置cell編碼解決中文高位位元組截斷
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
//設置cell字元類型的值
if(vc.get(i*cols+j) == null){
cell.setCellValue("");
}else{
if(num[j] == 0){
cell.setCellValue(vc.get(i*cols+j).toString());
}else{
cell.setCellValue(Double.parseDouble(vc.get(i*cols+j).toString()));
}
//記錄每列的長度
if(vc.get(i*cols+j).toString().getBytes().length > length[j]){
length[j] = vc.get(i*cols+j).toString().getBytes().length;
}
}
//設定對齊方式
if(align[j] == 1){
cell.setCellStyle(styleLeft);
}
if(align[j] == 2){
cell.setCellStyle(styleCenter);
}
if(align[j] == 3){
cell.setCellStyle(styleRight);
}
}
rownum++;
}
}

/**
* 生成統計結果行
* @param stat 統計結果
* @param align 對齊方式,1為左,2為中,3為右
*/
public void createStat(String stat,int align){
//生成統計結果行
HSSFRow row = sheet.createRow((short)rownum);
//生成統計結果格
HSSFCell cell = row.createCell((short)0);
//生成統計結果單元格樣式
HSSFCellStyle style = wb.createCellStyle();

//設定統計結果字體
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("新宋體");
font.setColor(HSSFColor.BLACK.index);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);

//設定標題框格式
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);

//設定對齊方式

if(align == 1){
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
}
if(align == 2){
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
}
if(align == 3){
style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}

//設置cell編碼解決中文高位位元組截斷
cell.setEncoding(HSSFCell.ENCODING_UTF_16);

//設定單元格文字合樣式
cell.setCellValue(stat);
cell.setCellStyle(style);

for(int i=1;i<cols;i++){
cell = row.createCell((short)i);
cell.setCellStyle(style);
cell.setCellValue("");
}

//設定合並的單元格
sheet.addMergedRegion(new Region(rownum,(short)0,rownum,(short)(cols-1)));

//當前行自增
rownum++;
}

/**
* 設置頁眉
* @param header 頁眉內容
* @param align 對齊方式,1為左,2為中,3為右
*/
public void createHeader(String header,int align){
HSSFHeader head = sheet.getHeader();
if(align == 1){
head.setLeft(header);
}
if(align == 2){
head.setCenter(header);
}
if(align == 3){
head.setRight(header);
}
}

/**
* 設置頁腳
* @param footer 頁腳內容
* @param align 對齊方式,1為左,2為中,3為右
*/
public void createFooter(String footer,int align){
HSSFFooter foot = sheet.getFooter();
if(align == 1){
foot.setLeft(footer);
}
if(align == 2){
foot.setCenter(footer);
}
if(align == 3){
foot.setRight(footer);
}
}

/**
* 設定頁腳的頁面值
* @param align 對齊方式,1為左,2為中,3為右
*/
public void createPage(int align){
HSSFFooter foot = sheet.getFooter();
if(align == 1){
foot.setLeft("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
if(align == 2){
foot.setCenter("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
if(align == 3){
foot.setRight("Page:" + HSSFFooter.page() + "/" + HSSFFooter.numPages());
}
}

/**
* 生成EXCEL文件
*/
public void createFile() throws Exception{
for(int i=0;i<length.length;i++){
sheet.setColumnWidth((short)i,(short)(length[i]*2*200));
}
FileOutputStream fileOut = new FileOutputStream(excelFile);
wb.write(fileOut);
fileOut.close();
}
}

B. 淺談JAVA讀寫Excel的幾種途徑

讀寫Excel文件需要使用Excel類庫,如Free Spire.XLS for Java.

讀取Excel內容:

//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//遍歷工作表的每一行
for(inti=1;i<sheet.getLastRow()+1;i++){
//遍歷工作的每一列
for(intj=1;j<sheet.getLastColumn()+1;j++){
//輸出指定單元格的數據
System.out.print(sheet.get(i,j).getText());
System.out.print(" ");
}
System.out.print(" ");
}

寫入內容:

//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//在單元格A1寫入新數據
sheet.getCellRange("A1").setText("你好");
//保存文檔
wb.saveToFile("寫入Excel.xlsx",ExcelVersion.Version2016);

C. 怎樣在java中導出xls文件

給你些小例子!用的是poi
package com;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class CreateXL {
/**
* 制定EXCEL要存放的文件位置,假定在D盤的test目錄下
*/
public static String outputFile="C:/Users/chentx/Desktop/test.xls";
public static void main(String[] args) {
try {
//創建新的Excel工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//在Excel中建一個工作表,其名為默認值
//如果建造一張為"ucap欄位"的工作表,那麼語句就是HSSFSheet sheet =workbook.createSheet("ucap欄位");
HSSFSheet sheet =workbook.createSheet();
//在索引0的位置創建行(最頂端的行)
HSSFRow row = sheet.createRow(0);
//在索引0的位置創建單元格(左上端)
HSSFCell cell = row.createCell(0);
//定義單元格為字元串類型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//在單元格中輸入一些內容
cell.setCellValue("field1");
//begin,設置單元格格式-----------------------------------
HSSFFont font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);//設置紅色
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//設置粗體
//創建格式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
//應用格式
cell.setCellStyle(cellStyle); //設置格式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);//定義單元格為字元串類型
cell.setCellValue("陳天翔霸氣");//設置文本內容
//end,------------------------------------------------
//輸出文件流
FileOutputStream fOut = new FileOutputStream(outputFile);
//把相應的excel工作表保存到硬碟上
workbook.write(fOut);
fOut.flush();
fOut.close();//關閉文件,操作結束
System.out.println("文件生成完畢....");
} catch (Exception e) {
System.out.println("已運行出錯" + e);
}
}
}

/*******************************************************************************************************/
package com;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadXL {
public static String fileToBeRead="C:/Users/chentx/Desktop/test.xls";
public static void main(String[] args) {
try {
//創建對excel工作表文件的引用
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
/* 創建對工作表的引用,本例按名引用(工作簿名Sheet0)
* HSSFSheet sheet = workbook.getSheet("Sheet0");
* 或者按索引引用
* HssfSheet sheet = workbook.getSheetAt(0);
*/
HSSFSheet sheet = workbook.getSheetAt(0);
//讀取左上端單元
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell(0);
//拿到讀出的內容
String mes = cell.getStringCellValue();
System.out.println("拿到的信息:" + mes);
} catch (Exception e) {
e.printStackTrace();
}
}
}

D. java如何輸出xls格式的Excel表格文件

有個開源的東東-jxl.jar,可以到http://sourceforge.net/project/showfiles.php?group_id=79926下載。
一.讀取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!=null&&sheet.length>0){
//對每個工作表進行循環
for(int i=0;i<sheet.length;i++){
//得到當前工作表的行數
int rowNum = sheet[i].getRows();
for(int j=0;j<rowNum;j++){
//得到當前行的所有單元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
//對每個單元格進行循環
for(int k=0;k<cells.length;k++){
//讀取當前單元格的值
String cellValue = cells[k].getContents();
sb.append(cellValue+" ");
}
}
sb.append(" ");
}
sb.append(" ");
}
}
//最後關閉資源,釋放內存
wb.close();
return sb.toString();
}
二.寫入Excel文件
這里有很多格式了,比如文本內容加粗,加上某些顏色等,可以參考jxl的api,同時還推薦一篇不錯的文章:http://www.ibm.com/developerworks/cn/java/l-javaExcel/?ca=j-t10
/**生成一個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;i<10;i++){
for(int j=0;j<5;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!=null&&sheet.length>0){
//對每個工作表進行循環
for(int i=0;i<sheet.length;i++){
if(breakSheet)
break;

//得到當前工作表的行數
int rowNum = sheet[i].getRows();

boolean breakRow = false;

for(int j=0;j<rowNum;j++){
if(breakRow)
break;
//得到當前行的所有單元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
boolean breakCell = false;
//對每個單元格進行循環
for(int k=0;k<cells.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=true&characterEncoding=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();
}

E. java怎麼把xls格式的文件另存為xlsx文件,不能直接改後綴名

那就需要一個同時兼容老版本的xls和新版本的xlsx的庫 這樣的庫可能不太多啊 但應該是可以搜到的

F. java和excel

1:excel表頭設置
文件->頁面設置->工作表,在「頂端標題行」里選擇設置,比如第1行作為表頭可以輸入$1:$1
2:mysql
獲取
表頭信息
use
information_schema
select
*
from
columns
where
table_name='表名';
show
columns
from
表名;

G. 怎麼用xls文件生成java文件

去學學怎麼用POI吧
POI可以到www.apache.org下載到。實際運行時,需要有poi包就可以了。HSSF提供給用戶使用的對象在rg.apache.poi.hssf.usermodel包中,主要部分包括Excel對象,樣式和格式,還有輔助操作。有以下幾種對象:
HSSFWorkbook excel的文檔對象
HSSFSheet excel的表單
HSSFRow excel的行
HSSFCell excel的格子單元
HSSFFont excel字體
HSSFDataFormat 日期格式

H. excel往java中導入怎麼解決

1、加入依賴的jar文件:

1
2
3

引用:
*mysql的jar文件
*Spring_HOME/lib/poi/*.jar

2、編寫資料庫鏈接類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

package com.zzg.db;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbUtils {
private static Connection conn;

static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","123456");
} catch (Exception e) {
e.printStackTrace();
}
}

public static Connection getConn() {
return conn;
}

public static void setConn(Connection conn) {
DbUtils.conn = conn;
}
}

3、編寫資料庫操作類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

package com.zzg.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ExcuteData {
private PreparedStatement pstmt;
public boolean ExcuData(String sql) {
Connection conn = DbUtils.getConn();
boolean flag=false;
try {
pstmt = conn.prepareStatement(sql);
flag=pstmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
}

4、編寫Excel表格實體類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

package com.zzg.model;

public class TableCell {
private String _name;
private String _value;

public String get_name() {
return _name;
}

public void set_name(String _name) {
this._name = _name;
}

public String get_value() {
return _value;
}

public void set_value(String _value) {
this._value = _value;
}
}

5、編寫主鍵生成方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

package com.zzg.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class GenericUtil {
public static String getPrimaryKey()
{
String primaryKey;
primaryKey = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
Random r = new Random();
primaryKey +=r.nextInt(100000)+100000;
return primaryKey;
}
}

6、編寫Excel操作類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168

package com.zzg.deployData;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.zzg.db.ExcuteData;
import com.zzg.model.TableCell;
import com.zzg.util.GenericUtil;

public class OperExcel<T extends Serializable> {
private HSSFWorkbook workbook;
private String tableName;
private Class<T> type;
private String sheetName;

public OperExcel(File excelFile, String tableName, Class<T> type,
String sheetName) throws FileNotFoundException,
IOException {
workbook = new HSSFWorkbook(new FileInputStream(excelFile));
this.tableName = tableName;
this.type = type;
this.sheetName = sheetName;
InsertData();
}

// 向表中寫入數據
public void InsertData() {
System.out.println("yyy");
ExcuteData excuteData = new ExcuteData();
List<List> datas = getDatasInSheet(this.sheetName);
// 向表中添加數據之前先刪除表中數據
String strSql = "delete from " + this.tableName;
excuteData.ExcuData(strSql);
// 拼接sql語句
for (int i = 1; i < datas.size(); i++) {
strSql = "insert into " + this.tableName + "(";
List row = datas.get(i);
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
if (n != row.size() - 1)
strSql += excel.get_name() + ",";
else
strSql += excel.get_name() + ")";
}
strSql += " values (";
for (short n = 0; n < row.size(); n++) {
TableCell excel = (TableCell) row.get(n);
try {
if (n != row.size() - 1) {
strSql += getTypeChangeValue(excel) + ",";
} else
strSql += getTypeChangeValue(excel) + ")";
} catch (RuntimeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//執行sql
excuteData.ExcuData(strSql);
}
}

/**
* 獲得表中的數據
* @param sheetName 表格索引(EXCEL 是多表文檔,所以需要輸入表索引號)
* @return 由LIST構成的行和表
*/
public List<List> getDatasInSheet(String sheetName) {
List<List> result = new ArrayList<List>();
// 獲得指定的表
HSSFSheet sheet = workbook.getSheet(sheetName);
// 獲得數據總行數
int rowCount = sheet.getLastRowNum();
if (rowCount < 1) {
return result;
}
// 逐行讀取數據
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
// 獲得行對象
HSSFRow row = sheet.getRow(rowIndex);
if (row != null) {
List<TableCell> rowData = new ArrayList<TableCell>();
// 獲得本行中單元格的個數
int columnCount = sheet.getRow(0).getLastCellNum();
// 獲得本行中各單元格中的數據
for (short columnIndex = 0; columnIndex < columnCount; columnIndex++) {
HSSFCell cell = row.getCell(columnIndex);
// 獲得指定單元格中數據
Object cellStr = this.getCellString(cell);
TableCell TableCell = new TableCell();
TableCell.set_name(getCellString(
sheet.getRow(0).getCell(columnIndex)).toString());
TableCell.set_value(cellStr == null ? "" : cellStr
.toString());
rowData.add(TableCell);
}
result.add(rowData);
}
}
return result;
}

/**
* 獲得單元格中的內容
*
* @param cell
* @return result
*/
protected Object getCellString(HSSFCell cell) {
Object result = null;
if (cell != null) {
int cellType = cell.getCellType();
switch (cellType) {

case HSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_NUMERIC:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA:
result = cell.getNumericCellValue();
break;
case HSSFCell.CELL_TYPE_ERROR:
result = null;
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = null;
break;
}
}
return result;
}

// 根據類型返回相應的值
@SuppressWarnings("unchecked")
public String getTypeChangeValue(TableCell excelElement)
throws RuntimeException, Exception {
String colName = excelElement.get_name();
String colValue = excelElement.get_value();
String retValue = "";
if (colName.equals("id")) {
retValue = "'" + GenericUtil.getPrimaryKey() + "'";
return retValue;
}
if (colName == null) {
retValue = null;
}
if (colName.equals("class_createuser")) {
retValue = "yaa101";
return "'" + retValue + "'";
}
retValue = "'" + colValue + "'";
return retValue;
}
}

7、編寫調用操作Excel類的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

package com.zzg.deployData;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DeployData {
private File fileOut;

public void excute(String filepath) {
fileOut = new File(filepath);
this.deployUserInfoData();
}

public void deployUserInfoData() {
try {
new OperExcel(fileOut, "test", Object.class, "Sheet1");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

8、編寫客戶端

1
2
3
4
5
6
7
8
9
10

package com.zzg.client;

import com.zzg.deployData.DeployData;

public class DeployClient {
public static void main(String[] args) {
DeployData deployData = new DeployData();
deployData.excute("D://test.xls");
}
}

I. java怎樣讀寫*.xls表的名稱

用file去寫。懂嗎?文件名稱是file,內容是jxl.jar可以讀的。比如用IO流寫到磁碟上,就用FileOutputStream ot = new FileOutputStream("C:\\Users\\xy\\Desktop\\key1.xls");
使用response,那麼就在返回頭里寫入文件的名稱格式

J. java xls下載方法

String 文件名 = 文件路徑.substring(getWJLJ().lastIndexOf(File.separator)+1);

response.setContentType("appication/pdf");//下載東西的格式
response.setHeader("Content-disposition", "attachment;文件名="+文件名);
try {
FileInputStream fis = new FileInputStream(文件路徑);
java.io.OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = fis.read(b))!=-1){
os.write(b, 0, len);
}
os.flush();
os.close();
fis.close();
思路就是,獲取文件名字和文件路徑,知道文件格式,創建IO進行下載。