와챠의 우당탕탕 코딩 일기장

[Android/Kotlin] Create a Word File/워드 파일 생성하기!!(.docx)/XWPFRun 본문

코딩 일기장/Android(Kotlin)

[Android/Kotlin] Create a Word File/워드 파일 생성하기!!(.docx)/XWPFRun

minWachya 2022. 5. 25. 15:31
반응형

요즘 여기저기서 AndroidStudio로 파일 만들기를 많이,,,접하게 되어서 궁금해져서 만들어봄

더 많은 활용은 더 공부해봐야할듯

일단 파일 생성까진 했으니 올려두기

 

결과 화면 먼저


1. 라이브러리 추가

implementation 'org.apache.poi:poi-ooxml:4.1.2'
implementation 'javax.xml.stream:stax-api:1.0'

+ minSdk로 26으로 변경해준다^__^

minSdk 26 // 21

 

2. Manifest에 파일 읽고 쓰기 위한 권한 추가

<!--파일 읽고 쓰기-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 

3. xml 만들기

나는 캡쳐하기 기능도 만들어서,,버튼이 있음,,무시해주세요

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 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"
    tools:context=".MainActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/btnCreateFile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_btn_create_file"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/btnCreateFile" />


    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

 

4. kt 코드 짜기

package com.example.mycapture

import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.example.mycapture.databinding.ActivityMainBinding
import org.apache.poi.xwpf.usermodel.XWPFDocument
import org.apache.poi.xwpf.usermodel.XWPFParagraph
import org.apache.poi.xwpf.usermodel.XWPFRun
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

private lateinit var binding: ActivityMainBinding
private const val TAG = "mmmMainActivity"

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        // 권한 허용 묻기
        requestPermission()

        // <파일 생성하기> 버튼 클릭
        binding.btnCreateFile.setOnClickListener {
            // 파일에 생성+작성+저장
            createWordFile(binding.editText.text.toString())
        }
    }

    // 권한 묻는 메소드
    private fun requestPermission() {
        ActivityCompat.requestPermissions(this@MainActivity,
            arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
            PackageManager.PERMISSION_GRANTED)
    }

    // 파일 생성하고 저장하는 메소드
    private fun createWordFile(text: String) {
        // 폴더 생성(해당 경로의 폴더가 존재하지 않으면 해당 경로에 폴더 생성)
        val folderPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString() + "/MyCapture/"
        val folder = File(folderPath)
        if (!folder.isDirectory) folder.mkdir()

        // 폴더 경로에 파일 생성 + 최종 저장
        try {
            val xwpfDocument = XWPFDocument()
            val xwpfParagraph: XWPFParagraph = xwpfDocument.createParagraph()
            val xwpfRun: XWPFRun = xwpfParagraph.createRun()

            xwpfRun.setText(text)
            xwpfRun.fontSize = 24

            val fileOutputStream = FileOutputStream(folderPath + "Test.docx")
            xwpfDocument.write(fileOutputStream)

            fileOutputStream.flush()
            fileOutputStream.close()
            xwpfDocument.close()

            Toast.makeText(applicationContext, "파일을 성공적으로 저장했습니다.", Toast.LENGTH_SHORT).show()
        }
        catch (e: Exception){
            e.printStackTrace()
            Toast.makeText(applicationContext, "파일 쓰기/저장 중 문제가 발생했습니다.", Toast.LENGTH_SHORT).show()
            return
        }
    }

}

+ 참고1) folderPath + "Test.docx" 경로 찍어보면 이렇게 나온다.

/storage/emulated/0/Documents/MyCapture/Test.docx

 

+ 참고2) XWPFRun의 더 많은 기능은... 여기서 확인 가능

 

참고

https://www.youtube.com/watch?v=2oT5heXHa94 

 

https://programmerworld.co/android/how-to-create-microsoft-word-document-docx-file-from-your-android-app/

 

How to create Microsoft Word Document (.docx) File from your Android App? - programmerworld

This video shows the steps to develop a method to create the Word Document File in your Android App. This uses the apache poi library for the same. It takes the content of the file as an input from the… Read More How to create Microsoft Word Document (.d

programmerworld.co

 

https://poi.apache.org/apidocs/dev/org/apache/poi/xwpf/usermodel/XWPFRun.html

 

XWPFRun (POI API Documentation)

Whether the bold property shall be applied to all non-complex script characters in the contents of this run when displayed in a document. This formatting property is a toggle property, which specifies that its behavior differs between its use within a styl

poi.apache.org

 

반응형
Comments