如何使用C#将TXT转换为Excel

如何使用C#将TXT转换为Excel

将 TXT 文件转换为 Excel 格式,便于在分布式环境中使用结构化或半结构化文本数据工作。 使用 Aspose.Cells for .NET,开发人员可以将平板文本文件转换为 Excel 格式(.xlsx)而不需要 Microsoft Excel。

為什麼要將 TXT 轉換為 Excel?

  • 数据结构改进:- 将简单的文本转换为支持基于细胞的组织、公式和风格的格式。

  • 自动化:- 自动大批文本文件处理到分布表进行报告或分析。

  • 整合準備好:- 轻松地将 TXT 数据集成到 .NET 应用程序中,用于出口、共享或处理。

步骤指南将 TXT 转换为 Excel

步骤 1: 通过 NuGet 安装 Aspose.Cells

从 NuGet 安装图书馆:

dotnet add package Aspose.Cells

步骤2:设置 Aspose.Cells 许可证

设置许可证访问完整功能:

Metered matered = new Metered();
matered.SetMeteredKey("PublicKey", "PrivateKey");

步骤3:下载 TXT 文件

Create a new Workbook by loading the .txt file:

Workbook workbook = new Workbook("input.txt");

步骤4: TXT 内容作为 Spreadsheet 转换

文本内容自动分布并将其放入工作表细胞中。

步骤5:保存作为Excel

将加载文本作为 Excel 文件导出:

workbook.Save("TXT_to_Excel.xlsx", SaveFormat.Xlsx);

常见问题和解决方案

1、文件不适当加载

  • Solution: Ensure the .txt file path is correct and the content is properly formatted with delimiters (tabs, commas, etc.).

二、格式化错误

  • 解决方案:考虑提前处理文本文件或在将其上传到工作簿之前使用自定义分解逻辑。

3、保存格式错误

  • Solution: Confirm you are using the appropriate SaveFormat when exporting to .xlsx.
 中文