打开一个模板.xls并写入2个单元格的简单方法是什么?

我有一个excel的模板,我想打开并写入sheet2两个不同的单元格中的两件事情。 我在互联网上search,但有一些东西在代码中,我不需要,如果我试图清理代码让我错误。 我想要一个简单的方法写在Excel中,并保存他。

如果您需要使用POCO进行处理,您可以使用我的工具Npoi.Mapper 。 它也是基于NPOI。 像下面的C#代码,但你可以很容易地转换为VB.NET:

var mapper = new Mapper("Book1.xlsx"); mapper.Put(products, "sheet1", true/*overwrite existing rows*/); mapper.Put(orders, "sheet2", false/*append rows*/); mapper.Save("Book1.xlsx"); 

“我想要一个简单的方法写在Excel中,并保存”

你可以使用NPOI库,也可以这样避免繁琐的Microsoft Office依赖Excel for interop。

一个简短的自制例子:

 Imports NPOI Imports NPOI.HSSF.UserModel Imports NPOI.HSSF.Util Imports NPOI.SS.UserModel Imports NPOI.SS.UserModel.Charts Imports NPOI.SS.Util Imports NPOI.XSSF.UserModel Dim WorkBookFile As String = "C:\MyWorkBook.xlsx" ' Create the excel workbook instance. Dim workbook As IWorkbook = Nothing ' Load the workbook. Using file As New FileStream(WorkBookFile, FileMode.Open, FileAccess.Read) workbook = New XSSFWorkbook(file) End Using ' Get the first sheet. Dim sheet As ISheet = workbook.GetSheetAt(0) ' Get the first row. Dim row As IRow = sheet.GetRow(0) ' Create a cell. Dim cell As ICell = row.CreateCell(1) ' Get the cell value. If String.IsNullOrEmpty(cell.StringCellValue) Then ' If value is emty then... Set cell value. cell.SetCellValue("This is a test") End If ' Save changes. Using sw As FileStream = File.Create(WorkBookFile) workbook.Write(sw) End Using 

请参阅其文档以获取正式入门示例。