导出HBase数据到Excel(Java代码)

 

一、主要代码

package com.sgcc.mcsas.bigdata.tool;

import com.sgcc.mcsas.bigdata.service.HBaseServiceImpl;
import com.sgcc.mcsas.bigdata.service.IHBaseService;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dwxx-120 on 2016/7/12.
 */
public class Export {

    private static IHBaseService service = new HBaseServiceImpl();
    private static final int count = 5;//记录数
    private static final String fileName = "D:/hbase_export.xls";

    public static void exportExcel(List<String> tableNames) throws Exception {
        //创建excel文件
        File file = new File(fileName);
        if (!file.exists()) {
            file.createNewFile();
        }

        //设定输出流
        FileOutputStream fos = new FileOutputStream(file);
        HSSFWorkbook book = new HSSFWorkbook();

        for (int k = 0; k < tableNames.size(); k++) {
            String tableName = tableNames.get(k);
            //取部分数据
            List<Result> results = service.getTopSomeRecords(tableName, "05M", count);

            //创建sheet
            HSSFSheet sheet = book.createSheet();
            book.setSheetName(k, tableName.replace(":", "_"));

            //为空返回
            if (results.size() == 0) {
                System.out.println(tableName + " has no data!");
                continue;
            }

            //生成表头
            HSSFRow header = sheet.createRow(0);
            HSSFCell header_rowkey = header.createCell(0);

            //rowkey表头
            header_rowkey.setCellValue("ROWKEY");
            //其他表头
            List<Cell> cells0 = results.get(0).listCells();
            for (int i = 0; i < cells0.size(); i++) {
                HSSFCell header_other = header.createCell(i + 1);
                String name = new String(cells0.get(i).getQualifier());
                header_other.setCellValue(name);
            }

            //遍历查询的数据
            for (int i = 0; i < results.size(); i++) {
                //一个Result创建一行
                HSSFRow data_row = sheet.createRow(i + 1);
                Result r = results.get(i);

                //设置rowkey的值
                String rowkey = new String(r.getRow());
                HSSFCell data_rowkey = data_row.createCell(0);
                data_rowkey.setCellValue(rowkey);

                //设置其他值
                List<Cell> cellList = r.listCells();
                for (int j = 0; j < cellList.size(); j++) {
                    HSSFCell data_other = data_row.createCell(j + 1);
                    data_other.setCellValue(new String(cellList.get(j).getValue()));
                }
            }
        }
        //写入
        book.write(fos);
    }

    public static void main(String args[]) throws Exception {
        //HBase表名
        List<String> list = new ArrayList<String>();
        list.add("mcsas:zxjc_aeolianvibration");
        list.add("mcsas:zxjc_airmoisture");
        list.add("mcsas:zxjc_airpresure");
        list.add("mcsas:zxjc_brakecable");
        exportExcel(list);
    }
}

 

二、HBase取数据主要代码(getTopSomeRecords)

/**
     * 获取指定位置向下N条记录
     */
    public List<Result> getTopSomeRecords(String tableName, String startRow,
                                           Integer count) throws HBaseException {
        Connection connection = null;
        Table hTable = null;
        try {
            connection = ConnectionFactory.createConnection(conf);
            hTable = connection.getTable(TableName.valueOf(tableName));
            Scan scan = new Scan();
            List<Result> results = new ArrayList<Result>();

            scan.setCacheBlocks(true);
            scan.setCaching(10000);
            scan.setStartRow(Bytes.toBytes(startRow));

            PageFilter filter = new PageFilter(count);
            scan.setFilter(filter);

            ResultScanner scanner = hTable.getScanner(scan);

            for (Result r : scanner) {
                results.add(r);
            }

            scanner.close();
            return results;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("获取数据出错: ", e);
            throw new HBaseException(HBaseException.UNKNOW_ERROR, "获取数据出错: ", e);
        } finally {
            closeHTable(hTable);
            closeConn(connection);
        }
    }

 

三、备注

1、本文中一个表对应一个sheet,最终只有一个Excel文件,里面含有多个sheet

 

2、本文只是取部分数据,将数据先存入List中,如果数据量太大,会导致内存溢出,另外Excel也不可能存放太多的数据,建议只取部分数据

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要导出 HBase 表中的数据,您可以使用 HBase Shell 命令或 HBase API。 1. HBase Shell 命令: - 进入 HBase Shell:在命令行中输入 hbase shell 命令。 - 导出数据:使用 scan 命令,并将结果保存到文件中。例如: ``` hbase> scan 'table_name', {RAW => true} | awk -F'\t' '{print $3,$4}' > /tmp/table_name.txt ``` 2. HBase API: - 获取 HBase 连接:使用 HBaseConfiguration 类获取 HBase 连接。 - 扫描数据:使用 HBaseAdmin 类获取 HBase 表,并使用 Table 类执行扫描操作。 - 保存数据:将扫描结果保存到文件中。 下面是一个使用 Java API 导出 HBase数据的示例: ```java import java.io.IOException; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; public class HBaseExport { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); try (Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("table_name")); ResultScanner scanner = table.getScanner(new Scan())) { for (Result result : scanner) { // Do something with the result. } } } } ``` ### 回答2: 编写校导出HBase数据的过程如下: 1. 配置HBase集群:确保HBase集群已正确配置和启动。 2. 编写Java程序:使用Java编写程序来导出HBase数据。 3. 导入相关依赖:在Java代码中导入HBase相关的依赖项,例如HBase的核心 jar 包。 4. 创建HBase连接:使用Java代码创建到HBase集群的连接。连接需要指定HBase的主机名和端口号。 5. 获取HBase表对象:通过HBase连接对象获取到需要导出数据的表对象。 6. 设置过滤器:使用过滤器来筛选需要导出数据。可以根据需求选择不同类型的过滤器,例如前缀过滤器、范围过滤器等。 7. 执行Scan操作:使用Scan对象进行数据扫描。Scan对象可以设置需要扫描的列族、列等信息。 8. 迭代处理结果:使用ResultScanner迭代扫描结果,并对每条数据进行处理。 9. 数据导出:根据需要将每条数据导出到文件、数据库或其他存储介质中。 10. 关闭连接:在程序执行结束后,关闭与HBase的连接。 以上步骤提供了一个基本的框架,可以根据具体需求进行调整和扩展。对于大规模数据导出,可能需要考虑分页查询、多线程处理等更高级的功能。同时,也需要注意处理可能出现的异常情况,例如连接失败、数据格式错误等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值