【问题标题】:How to write data in multiple cells in Excel using java?如何使用java在Excel中的多个单元格中写入数据?
【发布时间】:2013-10-29 10:37:46
【问题描述】:

我编写了一个在 Excel 表中写入数据的代码。在此我必须在多个单元格中写入数据。但它显示了一些错误。对于一个单元格,它能够更改数据。我保留 for 循环 用于更改多个单元格中的数据。为此,它显示错误。 谁能告诉我我哪里做错了。

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.lang.String;

import javax.swing.JOptionPane;

import jxl.Cell;

import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Sele1
{

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        String FileName = "C:\\Users\\u304081\\Desktop\\Java\\new.xlsx";

        try 
        {
            FileInputStream fileInputStream3 = new FileInputStream(FileName);
            File outputsheetfile1 = new File(FileName);
            if(outputsheetfile1.exists()) 
            {
                System.out.println("File existed");
                try
                {
                    XSSFWorkbook ObjWorkBook = new XSSFWorkbook(fileInputStream3);
                    XSSFSheet DriverTableSheet = ObjWorkBook.getSheetAt(0);
                    for(int i=1;i<3;i++)
                    {
                    XSSFRow row1 = DriverTableSheet.getRow(i);
                    XSSFCell Cell1 = row1.getCell(0);

                    System.out.println("Cell1"+ Cell1);
                    //System.out.println("Cell2"+ Cell2);
                     String str = "Abc";
                     Cell1.setCellValue(str);

                     FileOutputStream out1 = new FileOutputStream (FileName,false);
                     ObjWorkBook.write(out1);
                     fileInputStream3.close();
                    }

                } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }

我得到的错误是:

ObjWorkBook.write(out1);

`"poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"`

【问题讨论】:

    标签: java excel apache-poi


    【解决方案1】:
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Course Pack Resolution Details");
            outputFileName = outPut.getAbsolutePath(); 
            int rownum = 0;`enter code here`
            for (int i = 0; i < dataList.size(); i++) {
                Object[] objArr = dataList.get(i);
                HSSFRow row = sheet.createRow(rownum++);
    
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    sheet.autoSizeColumn((short) cellnum);
                    if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }
            if (outPut.exists()) {
                outPut.delete();
            }
            FileOutputStream out =
                    new FileOutputStream(outPut);
            workbook.write(out);
    

    DataList 是数组对象的 ArrayList,因此您可以输入任意数量的数据。

    数据列表示例:

    dataList.add(new Object[]{"Sr No.", "Cols1", "cols2", "cols3"......."colsn"});
    

    您可以在列表中插入的相应数据。此示例适用于 .xls 格式,如果您想要 .xlsx,请使用 xssfworkbook。

    可能对你有帮助。

    【讨论】:

    • 谢谢你,我正在尝试做同样的事情。但我正在检查不同行中的特定单元格。
    • 嗨,Umasri,你能告诉我你做得怎么样吗??
    【解决方案2】:

    你提到的错误:

    ObjWorkBook.write(out1); Here it is showing Error as "poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"
    

    似乎与您提到的将多个单元格中的数据写入excel的问题无关。

    你可能想看看这个:

    How can I link source to a jar package in eclipse?

    【讨论】:

      【解决方案3】:

      =======在播放框架中将数据写入excel文件===============

      HSSFWorkbook workbook = new HSSFWorkbook();
      HSSFSheet sheet = workbook.createSheet("Sample sheet");
      
      Map<String, Object[]> data = new HashMap<String, Object[]>();
      data.put("1", new Object[] {"empNo.", "name", "salary"});
      data.put("2", new Object[] {1, "John", 1500000d});
      data.put("3", new Object[] {2, "Sam", 800000d});
      data.put("4", new Object[] {3, "Dean", 700000d});
      
      Set<String> keyset = data.keySet();
      int rownum = 0;
      for (String key : keyset) {
          Row row = sheet.createRow(rownum++);
          Object [] objArr = data.get(key);
          int cellnum = 0;
          for (Object obj : objArr) {
              Cell cell = row.createCell(cellnum++);
              if(obj instanceof Integer) 
                  cell.setCellValue((Integer)obj);
              else if(obj instanceof String)
                  cell.setCellValue((String)obj);
              else if(obj instanceof Double)
                  cell.setCellValue((Double)obj);
          }
      }
      
      try {
          //new excel file created by fileoutput stream object 
          FileOutputStream out = 
                  new FileOutputStream(new File("/home/jagasan/workspace-playexcelApp/public/ExcelFile3.xlsx"));
          workbook.write(out);
          out.close();
          System.out.println("Excel written successfully..");
      
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      return ok("file reading is completed");
      

      =======从excel中读取数据并存储在playframework的数据库中=======

      public class Application extends Controller {
      
          /*
           * public Result index() { return
           * ok(index.render("Your new application is ready.")); }
           */
          public Result readExcel() throws FileNotFoundException {
              try{
                 InputStream ExcelFileToRead = new FileInputStream("/home/jagasan/workspace-play/excelApp/public/ExcelFile3.xlsx");
      
                  HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead); 
                  HSSFSheet sheet=wb.getSheetAt(0);
                  HSSFRow row;
                  HSSFCell cell;        
                  Iterator rows = sheet.rowIterator();
                  boolean flag=false;
                  while (rows.hasNext())
                  {
                      row=(HSSFRow) rows.next();
                      if(flag==false)
                      {
                          flag=true;
                          continue;
                      }
                      Iterator cells = row.cellIterator();
                      ExcelFile excelfile=new ExcelFile();
                      int i=0;
                      while (cells.hasNext())
                      {
                          cell=(HSSFCell) cells.next();
                          if(i==0)
                              excelfile.setEmpNo((int)cell.getNumericCellValue());
                          if(i==1)
                              excelfile.setName(cell.getStringCellValue());
                          if(i==2)
                              excelfile.setSalary(cell.getNumericCellValue());
                         i++;
      
                      }
                      excelfile.save();
      
                  }
              }
              catch(Exception e)
              {
                  e.printStackTrace();
                  System.out.println("error");
              }
              return ok("successful");
          }
      

      ======在 build.sbt=======

      使用依赖jar文件意味着apache API

      libraryDependencies ++= Seq(
        javaJdbc,
        cache,
        javaWs,
        "org.apache.poi" % "poi" % "3.8", "org.apache.poi" % "poi-ooxml" % "3.9"
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        • 2010-12-06
        相关资源
        最近更新 更多