创建一个新单元格,在Apache POI中复制以前单元格的样式..?

时间:2015-11-20 18:00:31

标签: java apache-poi

在我的java类中,我宣称像是这样的单元格:

HSSFCell cell = null;

我在许多地方使用这个单元来创建一个单元格并设置值,样式。像:

cell = row.createCell(1);               
cell.setCellValue("1234.00");
setCellStyle(currency, cell, workbook);

cell = row.createCell(2);               
setCellValue("2445.00");

现在,令人惊讶的是,第一个小区的数据格式正在应用于第二个小区。 任何人有任何想法? 我希望第二格的风格是没有的。第一个单元格的样式应该是setCellStyle()方法应用的数据格式。 但是,实际上我通过setCellStyle()方法应用了数据格式的两个单元格值。

setCellStyle()方法:

public void setCellStyle(String currency, HSSFCell cell, HSSFWorkbook workbook){

        HSSFCellStyle cellStyle = cell.getCellStyle();//I am using cell.getStyle() because the default cell style is not null for a HSSFCell

        HSSFDataFormat dataFormat = workbook.createDataFormat();

        if("GBP".equalsIgnoreCase(currency)){
            cellStyle.setDataFormat(dataFormat.getFormat("[$£-809]#,##0_);[Red]([$£-809]#,##0)"));                 
        }else (){
            cellStyle.setDataFormat(dataFormat.getFormat("$#,##0_);[Red]($#,##0)")); 
        }
}

1 个答案:

答案 0 :(得分:4)

现在您已更新帖子以显示setCellStyle方法,我可以看到问题。每个Cell都以默认CellStyle开头,并且它们共享相同的默认CellStyle。当您为第一个setCellStyle致电Cell时,您正在更改为所有单元格共享的默认CellStyle。这意味着您创建的任何其他单元格(未设置CellStyle)都会进行更改。此外,在您调用自己的setCellStyle的任何其他时间,它都会再次更改默认的单元格样式。

相反,请使用Workbook's createCellStyle method创建仅CellStyle只有Cell的新HSSFCellStyle cellStyle = workbook.createCellStyle();

import mechanize
from bs4 import BeautifulSoup
import urllib

username = 'username@yahoo.com'
password = 'password'

br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open("https://football.fantasysports.yahoo.com/f1/313652/transactions")
br.select_form(nr=0)
br.form["username"] = username
br.form["passwd"] = password
response = br.submit()
html_scrape = response.read()
soup = BeautifulSoup(html_scrape, "lxml")
index = 1
dropped = {}

for players in soup.select("table > tr > td > div"):
    player = players.find('a').get_text()
    try:
        if (players.find('h6').get_text() == ' To Waivers' ):
            dropped[index] = player
    except AttributeError:
        pass

    time = players.find('span',{'class':"Block F-timestamp Fz-xxs Nowrap"})
    if (time != None):
        try:
            nullplayer = dropped[index - 1]
            time = time.get_text()
            dropped[index] = time
        except KeyError:
            pass
    index += 1

count = 1
for items in dropped:
    if (count % 2 == 0):
        player = dropped[items - 1]
        time = dropped[items]
        print "%s dropped on %s" %(player, time)
    count += 1

如果您打算将多个单元格设置为相同的单元格样式,则应reuse the CellStyle objects

  

从工作簿创建新的单元格样式非常重要,否则您最终可能会修改内置样式,并且不仅会影响此单元格,还会影响其他单元格。