2014-12-19 104 views
0

在此代碼中,出現類工廠不可用的錯誤。本程序是關於基於分號轉換csv(逗號分隔值)文件int xls(Microsoft Excel)文件。有人能幫我解決嗎?在分號的基礎上使用C#將csv轉換爲xls

using Microsoft.Office.Interop.Excel; 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using Excel = Microsoft.Office.Interop.Excel; 
using Microsoft.Office.Core; 
using Microsoft.Office.Tools.Excel; 
namespace ReadWriteCSV 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Excel.Application excel = new Excel.Application(); 
      Excel.Workbook workBook = excel.Workbooks.Add(); 
      Excel.Worksheet sheet = workBook.ActiveSheet; 

      string fullPath = @"D:\Work\Sep-14\ReadWriteCSV\ReadWriteCSV\File\diff_16122014095440.csv"; 
      string[] fileRows = File.ReadAllLines(fullPath, Encoding.UTF8); 

      foreach (string rows in fileRows) 
      { 
       var columns = rows.Split(';'); 

       for (int j = 0; j < fileRows.Length; j++) 
       { 
        for (int i = 0; i < columns.Length; i++) 
        { 
         List<string> elements = new List<string>(); 
         foreach (string col in columns) 
         { 
          elements.Add(col); 
          sheet.Cells[i + 1, j + 1] = col; 
         } 
         } 
        } 
       } 
      workBook.SaveAs(@"D:\Work\Sep-14\ReadWriteCSV\ReadWriteCSV\File\WriteXls.xlsx"); 
      workBook.Close(); 
      } 
     } 
    } 

回答

0

使用Excel並將其保存爲XLSX

+1

我做了同樣的事情。請建議其他解決方案或在上述程序中找到錯誤 – 2014-12-19 11:54:25

0

你的問題如下打開CSV文件:使用字母,如A,B,C,d,E

Excel的索引列不是數字, F,G,H等等。

您需要將數字索引轉換爲字母索引。如果沒有超過26列的列,則可以使用ASCII作爲偏移量。

sheet.Cells[i + 1, ((char)(j+ 65)).ToString()] = col; //65 is ASCII for letter A 

編輯:

你的代碼中有一個問題。爲什麼你要在內部循環中重複遍歷列?與外部foreach循環相同。所有你需要的代碼是這樣的:

for (int i = 0; i< fileRows.length;i++) 
{ 
    string row = fileRows[i]; 
    string[] columns = row.Split(';'); 
    for (int j =0; j<columns.length;j++) 
     sheet.Cells[i + 1, ((char)(j+ 65)).ToString()] = columns[j]; 
} 

就是這樣。你不需要編寫內部循環,因爲它會花費你很多無用的處理。