使用超过“字符计数”的字符计数;Z”;在C#中
本文关键字:字符 字符计数 | 更新日期: 2023-09-27 17:59:53
我有一个数据集转储,它使用字符集类型的循环来查找第一个列字母。这对a-Z非常有效,但当我需要AA或AB时,我会不知所措。这是我正在使用的,是从我在网上找到的一些代码中重新编写的。我能做什么吗?
public void ExportToExcel(DataSet dataSet, string templatePath, int i, int h)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
FileInfo excelFileInfo = new FileInfo(templatePath);
Boolean fileOpenTest = IsFileLocked(excelFileInfo);
Excel.Workbook templateBook;
if (!fileOpenTest)
{ templateBook = excelApp.Workbooks.Open(templatePath); }
else
{ templateBook = (Excel.Workbook)System.Runtime.InteropServices.Marshal.BindToMoniker(templatePath); }
string tabName = lstQueryDumpSheet.Items[i].ToString();
Excel.Worksheet templateSheet = templateBook.Sheets[tabName];
// Copy DataTable
foreach (System.Data.DataTable dt in dataSet.Tables)
{
// Copy the DataTable to an object array
object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
// Copy the values to the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{ rawData[row, col] = dt.Rows[row].ItemArray[col]; }
}
// Calculate the final column letter
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{ finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1); }
finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);
// Fast data export to Excel
string dumpCellString = lstQueryDumpText.Items[i].ToString();
string dumpCell = dumpCellString.Split('=').Last();
string excelRange = string.Format(dumpCell + ":{0}{1}", finalColLetter, dt.Rows.Count + 1);
templateSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
}
您可以使用Excel将列索引转换为字母,反之亦然。
下面是一些VBA代码。你可以适应c#:
' Letter (AA) to index (27)...
MsgBox Sheet1.Columns("AA").Column
' Index (27) to letter (AA)...
MsgBox Mid$(Sheet1.Columns(27).Address, 2, 2)