1. 下载 NPIO相关dll
2. 读 Word (.docx) 文件示例:
using System;
using System.IO;
using UnityEngine;
using NPOI.XWPF.UserModel; // for .docx
using NPOI.SS.UserModel; // if you need additional support
using System.Text; // for StringBuilder
public class WordReader : MonoBehaviour
{
public string filePath; // Word file path
void Start()
{
if (!string.IsNullOrEmpty(filePath))
{
ReadWordFile(filePath);
}
else
{
Debug.LogError("Please set the path to the Word file.");
}
}
void ReadWordFile(string path)
{
try
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
// Open the Word document
XWPFDocument doc = new XWPFDocument(stream);
StringBuilder content = new StringBuilder();
// Read paragraphs
foreach (var para in doc.paragraphs)
{
content.AppendLine(para.Text);
}
// Output content to Console
Debug.Log(content.ToString());
}
}
catch (Exception e)
{
Debug.LogError("Error reading Word file: " + e.Message);
}
}
}
注意:① 在word打开时,读取会报错;② 只能读取每行文本,段落貌似无法读取。
3. 读Excel 文件(.xlsx
)文件示例:
using System;
using System.IO;
using UnityEngine;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public class ExcelReader : MonoBehaviour
{
public string filePath; // Excel file path
void Start()
{
if (!string.IsNullOrEmpty(filePath))
{
ReadExcelFile(filePath);
}
else
{
Debug.LogError("Please set the path to the Excel file.");
}
}
void ReadExcelFile(string path)
{
try
{
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
// Open the Excel workbook
IWorkbook workbook = new XSSFWorkbook(stream);
ISheet sheet = workbook.GetSheetAt(0); // 读取第一个工作表
StringBuilder content = new StringBuilder();
// 遍历行和列
for (int row = 0; row <= sheet.LastRowNum; row++)
{
IRow currentRow = sheet.GetRow(row);
if (currentRow != null) // 确保行不为空
{
for (int col = 0; col < currentRow.LastCellNum; col++)
{
ICell cell = currentRow.GetCell(col);
if (cell != null)
{
content.Append(cell.ToString() + "\t"); // 使用制表符分隔单元格
}
}
content.AppendLine(); // 行结束换行
}
}
// 输出内容到 Console
Debug.Log(content.ToString());
}
}
catch (Exception e)
{
Debug.LogError("Error reading Excel file: " + e.Message);
}
}
}