Home Backend Development Golang How Golang processes excel

How Golang processes excel

Oct 19, 2020 pm 02:40 PM
excel golang

The following column golang tutorial will introduce you to Golang's method of processing excel. I hope it will be helpful to friends in need!

How Golang processes excel

Previous articles about Golang were mainly explained based on Golang’s standard library. Today we will take a look at Golang’s An open source library that can be used to process xlsx files. First download the package

go get github.com/tealeg/xlsx
Copy after login

Let's see how to use this package through a simple example. This example mainly implements inputting column names and converting all the items in that column in the table. The data is displayed. The code is as follows:

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/tealeg/xlsx"
)

func main() {
	if len(os.Args) != 3 {
		fmt.Println("Usage: xlsx pathname sheetname")
		os.Exit(1)
	}

	xlsxFile, err := xlsx.OpenFile(os.Args[1])
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	sheet := xlsxFile.Sheet[os.Args[2]]
	if sheet == nil {
		fmt.Println("表单名不存在")
		os.Exit(1)
	}

	for {
		title := getStdinInput("请输入列名:")
		if title == "" {
			fmt.Println(title)
			continue
		}

		titleColIndex := findColByTitle(sheet, title)
		if titleColIndex == -1 {
			fmt.Println("列名不存在")
			continue
		}

		rowLen := len(sheet.Rows)
		result := []string{}
		for rowIndex := 1; rowIndex < rowLen; rowIndex++ {
			content := sheet.Cell(rowIndex, titleColIndex).String()
			result = append(result, content)
		}

		fmt.Println(result)
	}
}

func getStdinInput(hint string) string {
	fmt.Print(hint)
	scanner := bufio.NewScanner(os.Stdin)
	if scanner.Scan() {
		return scanner.Text()
	}

	return ""
}

func findColByTitle(sheet *xlsx.Sheet, title string) int {
	titleRow := sheet.Rows[0]
	for titleIndex, col := range titleRow.Cells {
		if col.String() == title {
			return titleIndex
		}
	}

	return -1
}
Copy after login

Let’s look at the main function first. The main function first performs command line parameter verification. To use this program, you need to use two parameters, one is the path to xlsx, and the other is the name of the form to be used. Then open the xlsx file and the corresponding form, read the column name through standard input, then find the column name in the corresponding form, and obtain all the data of the column by traversing all rows. Two functions are encapsulated here to read data from standard input and find the corresponding column index.

The getStdinInput() function receives a parameter as the input prompt statement. This function obtains the text of the standard input based on the scanner.

The findColByTitle() function passes in two parameters: the pointer of the form object and the column name. By looping through all the columns in the header row, find the matching column index and return it.

You can create a standard xlsx file yourself. The first line is the title line, and then test it with a utility program. I have used Python for Excel processing before, but I feel that Golang is more efficient.

The above is the detailed content of How Golang processes excel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

Solve complex financial calculations with 3 Excel financial functions Solve complex financial calculations with 3 Excel financial functions Jul 21, 2024 pm 06:39 PM

Original title: "These 3 Excel financial functions are undervalued again!" 》Author of this article: Xiaohua Editor of this article: Zhu Lan Recently, Xiaohua encountered an interesting question, which came from the soul of an old friend: How to choose between monthly annuity and private mutual insurance finance? The basic information of these two financial products is as follows: Monthly annuity: monthly payment of 1,000 yuan, annualized interest rate of 3%, 2-year term, and one-time withdrawal of principal and interest upon maturity. Mutual insurance finance: Pay a principal of 1,000 yuan every month, and the monthly principal will be calculated at 10% interest, with a 2-year term. There are 24 people participating in the same product. Every month, one person must receive all the principal and interest paid by others. The next month after receiving the payment, one person must pay an interest of 100 yuan/month. How to compare the pros and cons of these two financial products? we can

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

See all articles