.NET 资源文件到 Excel 文件转换器






2.88/5 (4投票s)
这个应用程序读取一个 .NET 资源文件,并将它的内容写入到 Microsoft Excel 文件中。

图 1
引言
这个应用程序将数据从 .NET 资源文件导出到 Excel 文件。代码使用了名为 Microsoft Excel 11.0 对象库的 COM 组件,它提供了操作 Excel 应用程序的 API。因此,在使用此代码之前,您需要添加对该 DLL 的引用,如图 1 所示。这篇文章展示了如何通过编程操作 Excel 文件以及 .NET 资源文件。
背景
.NET 中有一个名为本地化的功能,大多数 ASP.NET Web 应用程序开发人员都应该熟悉。我需要在我的一个项目中实现相同的功能,为此我需要为不同的语言创建资源文件。我为英语创建了一个资源文件,但我也需要相同键的多种语言的值,所以我必须将键值对放在 Excel 文件中,交给指定人员,以便他们在同一个 Excel 文件中编写其他语言的相应值。现在,将资源文件数据手动导出到 Excel 文件对我来说似乎非常耗时,因为有大量的资源文件(超过 100 个)。所以我决定首先开发一个小工具来为我完成这项任务。除了轻松完成我的任务外,我发现这非常有趣,因为我从中学习了很多。之后,我还开发了一个将数据从 Excel 文件导入回资源文件的工具。您可以在我的文章 Excel 到资源文件转换 中阅读它。

Using the Code
这是您可以在表单页面加载中放入的 Excel 应用程序初始化代码
// reference to Microsoft Excel object
Excel.Application exlObj = null;
// initializing the Excel application
exlObj = new Excel.Application();
// Showing the error message if any problem occurs in starting the Excel application
if (exlObj == null)
{
MessageBox.Show("Problem in starting Excel.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Windows.Forms.Application.Exit();
}
// you can keep the Excel application visible or invisible while writing to it
exlObj.Visible = false;
如何创建一个 Excel 工作簿和工作表来操作?
// creating Excel workbook
Excel.Workbooks workbooks = exlObj.Workbooks;
// "workbook.Add" method returns a workbook with specified template
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
// getting the collection of Excel sheets from workbook.
// However right now there is only one worksheet in the workbook
Sheets sheets = workbook.Worksheets;
// getting the worksheet from Sheet's collection.
// Keep in mind that in Excel, the index starts from 1
// and index 1 always gives the newly added worksheet
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
向工作簿添加新的工作表
// This method adds a new sheet to Sheet collection of workbook
// here Missing.Value signifies that these arguments are unknown
// we can also pass appropriate arguments if we wish
sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
命名或重命名工作表
// naming the worksheet. The name of the worksheet should not exceed 31 characters
if (fileName.Length > 30)
{
worksheet.Name = fileName.Substring(0, 29);
}
else
{
worksheet.Name = fileName;
}
处理工作表中的数据和格式
// get_range gives the object of a particular row from index1 to index2
Range range = worksheet.get_Range("A1", "B1");
// applying text format on a particular range. These can be applied on
// the whole worksheet too
range.Font.Bold = true;
// writing text to a cell
range.set_Item(1, 1, "KEY");
range.set_Item(1, 2,"VALUE");
// applying format on worksheet
worksheet.Columns.ColumnWidth = 40;
worksheet.Rows.WrapText = true;
worksheet.SaveAs(txtTargetPath.Text + "\\"+fileName +".xls"
, 1, null, null, false, false, null, null, null, null);
关注点
此代码使用的基本思想是操作 Excel 文件和 .NET 资源文件。我在这里展示的示例符合我的要求,并且我只实现了我探索中需要的东西。您可以将这篇文章作为进一步探索该主题的起点,因为您可以对 Excel 文件进行很多操作,甚至对 *.resx 文件进行一些操作。
历史
- 10 月 18 日,07:00:初始发布