2016-06-22 125 views
0

我使用Microsoft.Office.Interop.Excel从文本文件创建excel文件; 这里是我的代码问题文本到excel文件转换

private void button1_Click(object sender, EventArgs e) 
    { 
     // Reading the text file - StreamReader include System.IO namespace 
     StreamReader objReader = new StreamReader(@"C:\Users\pci218\Desktop\TextToExcelFormApplication\TextToExcelFormApplication\Text\pop3.txt");// Please give the file path 
     string sLine = ""; 
     ArrayList arrText = new ArrayList();// Include System.Collections.Generic namespace 
     while (sLine != null) 
     { 
      sLine = objReader.ReadLine(); 
      if (sLine != null) 
       arrText.Add(sLine); 
     } 
     callExcel(arrText, true); 
    } 

    private void callExcel(ArrayList arrText, bool value) 
    { 
     try 
     { 
      // Change Your String here 
      String textString = null; 
      foreach (var item in arrText) 
      { 
       textString = textString + item + Environment.NewLine; 
      } 
      Clipboard.SetText(textString); 
      Microsoft.Office.Interop.Excel.Application xlexcel; 
      Microsoft.Office.Interop.Excel.Workbook xlWorkBook; 
      Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; 
      object misValue = System.Reflection.Missing.Value; 
      xlexcel = new Excel.Application(); 
      // for excel visibility 
      //xlexcel.Visible = true; 
      // Creating a new workbook 
      xlWorkBook = xlexcel.Workbooks.Add(misValue); 
      // Putting Sheet 1 as the sheet you want to put the data within 
      xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
      // creating the range 
      Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1]; 
      CR.Select(); 
      xlWorkSheet.Paste(CR, false); 
      if (value == true) 
      { 
       try 
       { 
        // saving the file as .xls 
        xlWorkSheet.SaveAs(@"C:\Users\U0153056\Desktop\receivedNew.xls"); 
       } 
       catch (Exception) 
       { 
        MessageBox.Show("File already exist"); 
       } 
      } 
      else 
      { 
       try 
       { 
        // saving the file as .xlsx 
        xlWorkSheet.SaveAs(@"C:\Users\U0153056\Desktop\receivedNew.xlsx"); 
       } 
       catch (Exception) 
       { 
        MessageBox.Show("File already exist"); 
       } 
      } 
      xlexcel.Quit(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.ToString()); 
     } 
    } 

但我m到处 错误“与CLSID检索COM类工厂组件”。我没有在我的PC上安装微软办公室,这个问题呢?由于那m得到这个错误?任何人有想法.pls帮助。

回答

0

不幸的是,您无法安装Microsoft Office Excel 2007或更高版本,因此无法使用Microsoft.Office.Interop.Excel

...您必须安装Microsoft Office Excel 2007和Microsoft Office Word 2007或更高版本安装在您的计算机上。

检查this链接了解更多信息。

+0

是否有任何其他方式来转换文本到Excel而不使用Microsoft.Office.Interop.Excel .. –

+0

有几种方法,但他们已经过时,所以不能确定,但​​你可以检查[**这个**] (http://stackoverflow.com/a/11448322/1652222)和[** this **](http://forums.asp.net/post/4203658.aspx)链接。 – ManishChristian

+0

谢谢........... –