excel 行列转置,行列转换。附完整代码
**excel 行列转置,行列转换。
package excel;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;##
import java.io.File;`在这里插入代码片`
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Excel3 {
public static void main(String[] args) throws Exception {
File file = new File("d://a/a.xls");
FileOutputStream out = null;
FileInputStream input = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum();
int colNum = sheet.getRow(0).getLastCellNum();
HSSFWorkbook newWB = new HSSFWorkbook();
HSSFSheet sheet1 = newWB.createSheet();
for (int i = 0; i <= rowNum; i++) {
sheet1.createRow(i);
for (int j = 0; j < colNum; j++) {
sheet.getRow(i).getCell(j).setCellType(Cell.CELL_TYPE_STRING);
String s1 = sheet.getRow(i).getCell(j).getStringCellValue();
sheet1.getRow(i).createCell(j).setCellValue(s1);
}
}
for (int i = 0; i < colNum; i++) {
for (int j = i + 1; j < rowNum + 1; j++) {
if (sheet1.getRow(i).getCell(j) == null) {
sheet1.getRow(i).createCell(j);
}
sheet1.getRow(j).getCell(i).setCellType(Cell.CELL_TYPE_STRING);
String tmp = sheet1.getRow(i).getCell(j).getStringCellValue();
String aa = sheet1.getRow(j).getCell(i).getStringCellValue();
sheet1.getRow(i).createCell(j).setCellValue(aa);
sheet1.getRow(j).createCell(i).setCellValue(tmp);
}
}
try {
out = new FileOutputStream("d://a/b.xls");
newWB.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}**