我有一个excel的模板,我想在2个不同的单元格中打开和写入两个东西。我在互联网上搜索,但在我不需要的代码中有一些东西,如果我尝试清理该代码让我错误。我想用一种简单的方法在Excel中编写并保存。
答案 0 :(得分:2)
如果需要处理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");
答案 1 :(得分:0)
“我想在Excel中轻松写入并保存他”
您可以使用 NPOI 库,这样您就可以避免Excel
互操作的繁琐 Microsoft Office 依赖项。
一个简短的自制示例:
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
请参阅 Documentation 了解官方入门示例。