英文:
Loop through column cells in golang and excelize
问题
我很惊讶如何在Golang中循环遍历Excel表格的列单元格,这是我的Excel文件:
我尝试了下面这段代码,但是出于其他原因:
package main
import (
	"fmt"
	"github.com/xuri/excelize/v2"
)
func main() {
	f, err := excelize.OpenFile("pricematching.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	// 获取sheet1部分的所有行。
	rows, err := f.GetCellValue("sheet1", "A2")
	fmt.Print(rows, "\t")
}
请注意,我只提供了代码的翻译部分,不包括其他内容。
英文:
I was wondered how to loop over column cells of excel sheet in golang, here is my excel file:
I have tried this piece of code for other reason
package main
import (
	"fmt"
	"github.com/xuri/excelize/v2"
)
func main() {
	f, err := excelize.OpenFile("pricematching.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	// Get all the rows in the sheet1 section.
	rows, err := f.GetCellValue("sheet1", "A2")
	fmt.Print(rows, "\t")
}
答案1
得分: 3
无论你的 Excel 文件如何,这是读取每个单元格的方法:
xlsxFile, error := excelize.OpenFile(filePath)
for _, sheetName := range xlsxFile.GetSheetMap() {
   for rowIndex, rowValues := range xlsxFile.GetRows(sheetName) {
      for columnIndex, columnValue := range rowValues {
         // 在这里进行你想要的操作
      }
   }
}
英文:
No matter how's your excel file, this is the way to read each cell:
xlsxFile, error := excelize.OpenFile(filePath)
for _, sheetName := range xlsxFile.GetSheetMap() {
   for rowIndex, rowValues := range xlsxFile.GetRows(sheetName) {
      for columnIndex, columnValue := range rowValues {
         // do what ever you want here
      }
   }
}
答案2
得分: 0
不确定你具体需要什么,但这是一种获取某一列中所有单元格的简单方法(如果你知道要读取的行数):
package main
import (
    "fmt"
    "github.com/xuri/excelize/v2"
)
func main() {
    f, err := excelize.OpenFile("pricematching.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    columnName := "A"
    sheetName := "sheet1"
    totalNumberOfRows := 20
    for i := 1; i < totalNumberOfRows; i++ {
        cellName := fmt.Sprintf("%s%d", columnName, i)
        // fmt.Println(cellName)
        cellValue, err := f.GetCellValue(sheetName, cellName)
        fmt.Printf("%s\t", cellValue)
    }
}
英文:
Not sure what exactly you need, but this is a simple way to get all cells in a column (if you know how many rows you want to read):
package main
import (
    "fmt"
    "github.com/xuri/excelize/v2"
)
func main() {
    f, err := excelize.OpenFile("pricematching.xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
	columnName := "A"
	sheetName := "sheet1"
    totalNumberOfRows := 20
	for i := 1; i < totalNumberOfRows; i++ {
		cellName := fmt.Sprintf("%s%d", columnName, i)
		// fmt.Println(cellName)
		cellValue, err := f.GetCellValue(sheetName, cellName)
		fmt.Printf("%s\t", cellValue)
	}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论