2015-06-26 12 views
1

我有一個使用字符集類型循環的數據集轉儲找到第一列字母將其放入。這對AZ非常有用,但是當我需要AA或AB , 我很茫然。這是我使用的,從我在網上找到的一些代碼中重新編寫的。我可以做任何事嗎?在C#中使用過去「Z」的字符計數

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; 
     } 
+0

[http://stackoverflow.com/a/667902/2237785](http://stackoverflow.com/a/667902/2237785) – Bond

回答

0

您可以使用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)