Excel sheet的列名到列序号的转换

序列 seq=[a,b,…,z,aa,ab,…,az,ba,bb,…,bz,…,za,zb,…,zz,aaa,…]类似于excel的列名从小到大依次排列。任意给一字符串 s=[a-z]+(由a-z字符串组成的任意长度字符串),返回s是序列seq的第几个(0-based)字符串。第一种解法更好理解一些。相当于做进制转换。跟一般的进制转换有个小小的区别。比如字母A在最低位上代表0,在其他位上都代表1. 其他字母也同理。所以如果按26进制转化完毕后需要减1才是题目要求的结果。

解法1: 先计算1-based下标,返回时减1。注意,这个方法没考虑越界.

unsigned int ColumnToIndex(const char * const pCol)
{
	if (NULL == pCol)
		return 0;
	unsigned int oneBasedSum = 0;
	const char *p = pCol;
	while ('\0' != *p)
	{
		oneBasedSum = ((oneBasedSum*26) + (*p - 'a' + 1));
		p++;
	}
	return oneBasedSum - 1;
}


解法2: .直接计算0-based下标。

unsigned int GetColumnIdx(const char * const pch)
{
	unsigned int sum = 0;
	char ch;
	const char * i = pch;
	while (*i != '\0')
	{
		ch = *i - 'a';
		if (i!=pch)
			sum+=1; // 关键点在这里,sum进位前+1,不进位就不加
		sum = sum * 26 + ch;
		i++;
	}
	return sum;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache POI库来读取Excel Sheet并将其转换为Java类。下面是一个简单的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelReader { public static void main(String[] args) throws IOException { String excelFilePath = "path/to/excel/file.xlsx"; FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); Workbook workbook = new XSSFWorkbook(inputStream); Sheet sheet = workbook.getSheet("Sheet1"); Iterator<Row> iterator = sheet.iterator(); ArrayList<Employee> employees = new ArrayList<>(); while (iterator.hasNext()) { Row nextRow = iterator.next(); Iterator<Cell> cellIterator = nextRow.cellIterator(); Employee employee = new Employee(); while (cellIterator.hasNext()) { Cell nextCell = cellIterator.next(); int columnIndex = nextCell.getColumnIndex(); switch (columnIndex) { case 0: employee.setId((int) nextCell.getNumericCellValue()); break; case 1: employee.setName(nextCell.getStringCellValue()); break; case 2: employee.setAge((int) nextCell.getNumericCellValue()); break; } } employees.add(employee); } workbook.close(); inputStream.close(); // Do something with the employees list } } class Employee { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 在这个示例中,我们读取了名为“Sheet1”的Excel Sheet,并将其转换为一个包含Employee对象的ArrayList。你可以根据需要修改代码来适应你的Excel Sheet和Java类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值