와챠의 우당탕탕 코딩 일기장
[Android/Kotlin] Create a Word File/워드 파일 생성하기!!(.docx)/XWPFRun 본문
[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
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
'코딩 일기장 > Android(Kotlin)' 카테고리의 다른 글
[Android] Android Architecture Components(AAC)/안드로이드 아키텍처 컴포넌트 - 1. Lifecycles (0) | 2022.05.28 |
---|---|
[Android/Kotlin]Detect Screen Capture Event/캡쳐 탐지/캡쳐 시 스낵바 띄우기 (2) | 2022.05.27 |
[Android/Kotlin] PageIndicatorView/Viewpager indicator (0) | 2022.05.05 |
[Android/Kotlin] Lottie Animation/애니메이션 추가하기 (0) | 2022.05.04 |
[Android/Kotlin]CustomView: color 속성 추가하기 (0) | 2022.04.26 |