Please Enable JavaScript!
Gon[ Enable JavaScript ]

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

안드로이드 개발
반응형

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

환경: Android Studio

 

안드로이드 앱에서 만든 데이터는 가공해서 엑셀 파일로 출력이 가능합니다. 안드로이드 SDK에서 제공하는 것이 아니라 아파치(Apache) 에서 제공하는 라이브러리를 사용해야 합니다. 스마트폰에 설치한 엑셀 프로그램만 있으면 데이터를 보거나 편집할 수 있습니다. 또한 좀더 편한 작업을 위해 PC 로 파일을 옮겨서 작업하는 것도 가능합니다.

 

먼저 안드로이드 앱에서 원하는 데이터를 엑셀 파일로 저장하기 위해서는 라이브러리가 있어야 합니다. 아래 링크 주소를 따라 아파치 홈페이지에 접속하면 라이브러리 파일을 받을 수 있습니다. 화면에서 Binary Distribution 에 링크를 클릭하면 상세 페이지로 이동합니다.

http://poi.apache.org/download.html#POI-3.17

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

그림처럼 링크 주소를 클릭해서 mirror 사이트에 올라가 있는 파일을 다운받습니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 


압축을 해제하면 poi jar 파일을 볼 수 있습니다. 해당 파일을 안드로이드 프로젝트로 옮기겠습니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

안드로이드 스튜디오의 프로젝트 폴더에 보시면 app 바로 아래 libs 가 있을 겁니다. 원하는 외부 라이브러리를 이곳에 추가해야 합니다. 복사한 poi jar 파일을 붙여넣기 합니다. Copy 팝업창이 뜨면 OK 버튼을 눌러 복사를 시작합니다. 특별히 이름은 변경할 필요가 없습니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

외부 라이브러리를 붙여넣었다고 해서 바로 사용할 수 없습니다. 프로젝트가 라이브러리를 인식할 수 있도록 별도의 작업이 필요합니다. 오른쪽 마우스를 눌러 [Add As Library] 메뉴를 선택하면 끝납니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

화면 시나리오는 다음과 같습니다.

 

1.    아이디와 이름을 입력하고 LISTADD 를 누르면 바로 아래 ListView 로 추가

2.    EXCELSAVE 버튼을 누르면 ListView 에 추가한 데이터를 Excel 파일로 출력

 

시나리오 대로 아이디와 이름을 입력하고 LISTADD 에 추가합니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

추가한 데이터를 엑셀로 출력하기 위해 EXCELSAVE 버튼을 클릭합니다. 화면에 나타난 저장 메시지에는 파일의 위치가 나옵니다. 파일은 앱 패키지 아래 files 폴더에 있습니다

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

엑셀 파일을 클릭해 보세요. 사용할 애플리케이션 목록에는 자신의 스마트폰에 설치된 엑셀 뷰어가 모두 나타납니다. 그 중 하나를 선택합니다. 그러면 ListView 에 추가한 데이터를 모두 볼 수 있을 겁니다.  

안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법

 

이제 화면 구성과 입력한 데이터를 엑셀 파일로 출력하는 함수를 만들어 보겠습니다. 엑셀 파일을 생성하고 데이터를 추가하는 함수는 다음과 같습니다. HSSFWorkbook 클래스를 이용해서 Wrokbook 을 생성합니다. 그리고 Wrokbook 으로 시트, , 열을 만들어 데이터를 추가합니다

private void saveExcel(){
    Workbook workbook = new HSSFWorkbook();
    Sheet sheet = workbook.createSheet(); // 새로운 시트 생성

    Row row = sheet.createRow(0); // 새로운 행 생성
    Cell cell;

    // 1번 셀 생성과 입력
    cell = row.createCell(0); 
    cell.setCellValue("아이디"); 

    // 2번 셀에 값 생성과 입력
    cell = row.createCell(1);
    cell.setCellValue("이름");

    for(int i = 0; i < mItems.size() ; i++){ // 데이터 엑셀에 입력
        row = sheet.createRow(i+1);
        cell = row.createCell(0);
        cell.setCellValue(mItems.get(i).getId());
        cell = row.createCell(1);
        cell.setCellValue(mItems.get(i).getName());
    }

    File excelFile = new File(getExternalFilesDir(null),"user.xls");
    try{
        FileOutputStream os = new FileOutputStream(excelFile);
        workbook.write(os); 
    }catch (IOException e){
        e.printStackTrace();
    }
    Toast.makeText(getApplicationContext(),excelFile.getAbsolutePath()+"에 저장되었습니다",Toast.LENGTH_SHORT).show();
}

 

화면에서 이름과 아이디를 입력하고 ListView 에 추가하기 위한 Adapter 전체 소스입니다. ArrayAdapter Item 클래스는 사용자 정보를 담을 Model 클래스 입니다

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import display.samsung.workplace.R;
import display.samsung.workplace.model.Item;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

public class ItemAdapter extends ArrayAdapter<Item> {
    private ArrayList<Item> mItems;
    private Context mContext;

    public ItemAdapter(@NonNull Context context, int resource, ArrayList<Item> items) {
        super(context, resource, items);
        mItems = items;
        mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        View rowView= inflater.inflate(R.layout.item, null, true);

        TextView id = (TextView) rowView.findViewById(R.id.tv_item_id);
        TextView name = (TextView) rowView.findViewById(R.id.tv_item_name);

        id.setText(mItems.get(position).getId() );
        name.setText(mItems.get(position).getName());

        return rowView;
    }

    class ItemViewHolder extends RecyclerView.ViewHolder{
        private TextView id;
        private TextView name;
        ItemViewHolder(View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.tv_item_id);
            name = itemView.findViewById(R.id.tv_item_name);
        }
    }
}

 

사용자 정보를 저장할 Model 클래스입니다.

public class Item {

    private String id;
    private String name;

    public Item(String id, String name){
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

다음은 전체 Activity 소스 입니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import display.samsung.workplace.Adapter.ItemAdapter;
import display.samsung.workplace.model.Item;

public class ExcelActivity extends AppCompatActivity {

    EditText mEdtId;
    EditText mEdtName;
    ListView mLvData;
    ArrayList<Item> mItems;
    ItemAdapter mItemAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_excel);

        mEdtId = (EditText) findViewById(R.id.edt_id);
        mEdtName = (EditText) findViewById(R.id.edt_name);
        mLvData = (ListView) findViewById(R.id.lv_data);

        mItems = new ArrayList<Item>();
        mItemAdapter = new ItemAdapter(this, R.layout.item, mItems);
        mLvData.setAdapter(mItemAdapter);
    }

    // 리스트 Excel 저장
    public void onExcelSave(View v){
        // 엑셀에 저장한다.
        saveExcel();
    }

    // 입력한 값 리스트에 추가
    public void onListAdd(View v){
        // 리스트에 추가한다.
        String tvId = mEdtId.getText().toString();
        String tvName = mEdtName.getText().toString();

        mItems.add(new Item(tvId, tvName));

        // ListView 갱신
        mItemAdapter.notifyDataSetChanged();

        // 초기화
        mEdtId.setText("");
        mEdtName.setText("");
    }

    private void saveExcel(){
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet(); // 새로운 시트 생성

        Row row = sheet.createRow(0); // 새로운 행 생성
        Cell cell;

        // 1번 셀 생성과 입력
        cell = row.createCell(0);
        cell.setCellValue("아이디");

        // 2번 셀에 값 생성과 입력
        cell = row.createCell(1);
        cell.setCellValue("이름");

        for(int i = 0; i < mItems.size() ; i++){ // 데이터 엑셀에 입력
            row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellValue(mItems.get(i).getId());
            cell = row.createCell(1);
            cell.setCellValue(mItems.get(i).getName());
        }

        File excelFile = new File(getExternalFilesDir(null),"user.xls");
        try{
            FileOutputStream os = new FileOutputStream(excelFile);
            workbook.write(os);
        }catch (IOException e){
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(),excelFile.getAbsolutePath()+"에 저장되었습니다",Toast.LENGTH_SHORT).show();
    }
}

 

Activity 를 구현한 화면입니다.

 

activity_excel.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="display.samsung.workplace.ExcelActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_id"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:text="아이디"/>

        <EditText
            android:id="@+id/edt_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="4"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_name"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="1"
            android:text="이름"/>

        <EditText
            android:id="@+id/edt_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="4"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ListAdd"
            android:onClick="onListAdd"
            android:gravity="center"
            android:layout_weight="1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ExcelSave"
            android:onClick="onExcelSave"
            android:gravity="center"
            android:layout_weight="1"/>

    </LinearLayout>

    <ListView
        android:id="@+id/lv_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


</LinearLayout>
반응형
Posted by 녹두장군1
,