使用Java POI覆盖excel文件

时间:2012-06-13 11:18:41

标签: java apache-poi

我是Java POI的新手,我正在尝试使用Java POI覆盖excel文件。让我说清楚,我不想每次构建代码时都打开一个新的.xls文件但是代码我写的是这样做的。目的是,我将在excel上构建图表并从数据库中读取图表的值,并使用Java POI将其写入excel文件。这是我的代码:

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");

HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);

HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
    workbook.write(fos);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fos != null) {
        try {
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6 个答案:

答案 0 :(得分:1)

始终使用相同的文件名,当您运行程序时,它将覆盖该文件。

修改 如果要修改现有的Excel文件,请查看HERE并向下滚动到“阅读或修改现有文件”部分。

答案 1 :(得分:0)

问题是Apache POI不支持Excel文件格式的所有功能,包括图表。因此无法使用POI生成图表,并且在使用POI打开现有Excel文件并对其进行修改时,Excel文件中的某些当前“对象”可能会丢失,因为POI无法处理它并且在写入时仅写入生成的新信息和可以处理的现有信息。

Apache认为这是POI的一个缺陷。

我们对现有Excel文件进​​行了类似的处理,在其上填充了新数据,但现有的Excel文件仅包含格式样式,并且使用POI保留它们,但我认为图表很成问题。 POI无法尝试使用填充数据来更新现有图表。

答案 2 :(得分:0)

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.List;

public class WriteExcel {
    public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex)  throws InvalidFormatException, IOException {

        try {
            FileInputStream inputStream = new FileInputStream(new File(path));
            Workbook workbook = WorkbookFactory.create(inputStream);

            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = 1;

            for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
                Row row = sheet.createRow(++rowCount);
              //  int columnCount = 0;

                Cell cell = row.createCell(columnCount);
                cell.setCellValue((String) dataList.get(i));
            }

            inputStream.close();

            FileOutputStream outputStream = new FileOutputStream(path);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.util.List;

public class WriteExcel {
    public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex)  throws InvalidFormatException, IOException {

        try {
            FileInputStream inputStream = new FileInputStream(new File(path));
            Workbook workbook = WorkbookFactory.create(inputStream);

            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = 1;

            for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
                Row row = sheet.createRow(++rowCount);
              //  int columnCount = 0;

                Cell cell = row.createCell(columnCount);
                cell.setCellValue((String) dataList.get(i));
            }

            inputStream.close();

            FileOutputStream outputStream = new FileOutputStream(path);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 3 :(得分:0)

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class UserInput {

    public static Map getUserInput() throws InvalidFormatException, IOException {
        String userName = System.getProperty("user.name");
        String path = "";
        int indexofColumn = 10;
        Map inputFromExcel = new HashMap();
        InputStream inp = new FileInputStream(path);
        int ctr = 4;
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
        Row row = null;
        Cell cell = null;
            try{
                row = sheet.getRow(ctr);
                cell = row.getCell(indexofColumn); //Mention column no. which you want to read
                inputFromExcel.put("NBKID",cell.toString()) ;
                row = sheet.getRow(ctr+1);
                cell = row.getCell(indexofColumn);
                inputFromExcel.put("Password", cell.toString());
                row = sheet.getRow(ctr+2);
                cell = row.getCell(indexofColumn);
                inputFromExcel.put("NBKIDEmail",cell.toString());
                row = sheet.getRow(ctr+3);
                cell = row.getCell(indexofColumn);
                inputFromExcel.put("sourceExcel" ,cell.toString());

            } catch(Exception e) {
            }

        return inputFromExcel;
    }

}

答案 4 :(得分:0)

import java.util;

public class Main {
    public static void main(String[] args) {
        List<String> partyIdList = new ArrayList<String>();
        List<String> phNoList = new ArrayList<String>();
        String userName = System.getProperty("user.name");
        String path = "";
            try {
                Map data = new HashMap(UserInput.getUserInput());
                partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
                phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
                WriteExcel.writeFile1(partyIdList, path,0,1);
                WriteExcel.writeFile1(phNoList,path,1,0);

            } catch (Exception e) {
                throw new RuntimeException("Error while read excel Sheet" + e);
            }

    }
}

答案 5 :(得分:-1)

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ReadExcel {
    public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
        //System.out.println(path);
        List<String> ItemList = new ArrayList();
        InputStream inp = new FileInputStream(path);
        int ctr = 0;
        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
        Row row = null;
        Cell cell = null;
        boolean isNull = false;
        do{
            try{
                row = sheet.getRow(ctr);
                cell = row.getCell(indexofColumn); //Mention column no. which you want to read
                ItemList.add(cell.toString());
                //   System.out.println(cell.toString());
                ctr++;
            } catch(Exception e) {
                isNull = true;
            }

        }while(isNull!=true);
        inp.close();

        return ItemList;
    }
}