java 实现excel表行列转换规则
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package com.change;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class Change {
/**excel列转行
* @param n,表示截断excel的多少列为一行即数据数量
*/
public void rowcolumn( String inputfilename , String outputfilename) {
int n;
Workbook wb = null;
WritableSheet ws = null;
bel lable = null ;
WritableWorkbook wwb = null;
//大的第二行的插入行的起始位置
int starth = 0;
int c = 0;
try {
wb = Workbook.getWorkbook(new File(inputfilename));
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(wb == null)
{
return;
}
Sheet[] sheet = wb.getSheets();//获取工作簿表对象
if(sheet!=null && sheet.length > 0)
{
//创建一个工作簿对象
try {
wwb = Workbook.createWorkbook(new File(outputfilename));
if(wwb != null)
{
//创建一个可写入的表,第一个是工作簿表名,第二个是工作簿的位置
ws = wwb.createSheet("sheet1", 0);
}
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0 ; i < sheet.length ; i++)//这里一般是只有一张sheet
{
int rownum = sheet[i].getRows();//工作簿对象的行数
int column = sheet[i].getColumns();
System.out.println(rownum+","+column);
n=rownum+1;
for(int r = 0; r < column ; r++)
{
//得到当前行的所有单元格
Cell[] cell=sheet[i].getColumn(r);
System.out.println("cell:"+cell);
if(cell != null && cell.length > 0)
{
//写入excel文件的行数
//*****************************************************************
int hang = (r+1)*(((rownum-1)/rownum+1));
//插入位置应该接着上次插入的最后一行的下一行开始
for(int h = starth ; h < hang ; h ++)
{
//写入文件的行数
for(int ll = 0 ; ll < n ; ll++)
{
if(ll == 0)
{
lable = new bel(ll,
h,cell[0].getContents());
}else{
c++;
if(c>=cell.length)
{
// continue;
lable = new bel(ll,
h,"");
c=0;
}else{
lable = new bel(ll, h,cell[c].getContents());
System.out.println("----"+cell[c].getContents());
}
}
try {
ws.addCell(lable); //添加到excel
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
starth = hang;//把最后一行行号赋给第二个大行的插入位置
System.out.println("starh***"+starth);
}
}
}
}
try {
wwb.write();//写入excel文件
wwb.close();
}
catch (WriteException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Change change=new Change();
change.rowcolumn("f:\\tongye-1.xls", "f:\\tongye-1-1.xls");
}
}