用xlsx包读取Excel文件

http://blog.csdn.net/liu7788414/article/details/44587213#t4

xlsx包可以读取、写入Excel2007/2003文件并支持格式的设置。简单地来说,将Excel读取为数据框,以及将数据框写入为Excel文件都不是问题,而更加强大的是它能处理 Excel中的格式,比如合并单元格,设置列的宽度,设置字体和颜色等等。
如果只需要基本的读取/写入操作,那么其中的read.xlsx()和write.xlsx()应该就能满足大部分的需求了,其用法也很简单,看看帮助文档就了解了。此外,还有两个相应的函数read.xlsx2()和write.xlsx2(),按作者的话说,这两个函数使用了不同的实现方式,效率上会更高一些。
除了基本的读写操作之外,xlsx包还能进行格式方面的设置。下面是一个简单的例子,说明了如何创建工作簿和工作表,如何操作单元格等。

ind = read.table(url("http://yixuan.cos.name/cn/wp-content/uploads/2012/01/ind.txt"),sep= "\t");
library(xlsx);
# Create a new workbook
wb = createWorkbook();
# Create a new sheet witha name
sheet1 = createSheet(wb,"第一页");
# Set the zoom ratio when you open the Excel file
setZoom(sheet1, 50, 100);
# Set the width of columns
setColumnWidth(sheet1,1:100, 2.8);

# Create rows
rows = createRow(sheet1,1:40);
# Create cells for eachrow
cells = createCell(rows,1:73);
# Merge the first row intoone cell
addMergedRegion(sheet1, 1,1, 1, 73);
# Create the style fortitle cell
title_cell_style =CellStyle(wb,alignment = Alignment(horizontal = "ALIGN_CENTER"),font= Font(wb, "blue", 50, isBold = TRUE));
# Create the style forblack cells
black_cell_style =CellStyle(wb,border = Border(),fill = Fill(foregroundColor="black"));
# Get the first row
first_row =getRows(sheet1, 1);
# Get the title cell fromfirst row
title_cell =getCells(first_row, 1)[[1]];
# Set the value of thetitle cell
setCellValue(title_cell,"Read/Write Excel!");
# Set the style of thetitle cell
setCellStyle(title_cell,title_cell_style);
# Set the style of blackcells
tmp = mapply(function(x,y) setCellStyle(cells[[x, y]], black_cell_style),ind[, 1] 3, ind[, 2] 5);
# Save the workbook into afile
saveWorkbook(wb,"test.xlsx");
xlsx包是目前功能最全的操作Excel的R包,它只依赖于Java环境和rJava、xlsxjars两个包,在多种平台下都能运行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值