2012-08-05 4 views
5

C#을 사용하여 Excel 시트에 꽤 긴 텍스트를 추가하려고합니다.C#을 사용하여 Excel 시트에 텍스트 추가

worksheet.Cells[1, 1] = textString; 

결과는 여기에 있습니다 : :

내가 원하는 것은 :

제안이 코드를 사용할 수 있습니까?

+0

분할을 테스트하고 새로운 행을 생성 어레이의 각각의 요소를 추가한다. –

답변

10

이 효과를 얻으려면 텍스트를 클립 보드에 복사 한 다음 관련 셀에 붙여 넣어야합니다. 이 예제를 참조하십시오

참고 : 매우 긴 문자열을 textString으로 설정하십시오.

시도 AND 바꿈에

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Windows.Forms; 
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      //~~> Change Your String here 
      String textString = "I'm trying to add a pretty long text into the Excel sheet by using sheet. I use this code:" + Environment.NewLine + 
           "worksheet.Cells[1, 1] = textString;" + Environment.NewLine + 
           "The result is here:"; 

      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(); 
      xlexcel.Visible = true; 

      //~~> Add a new a workbook 
      xlWorkBook = xlexcel.Workbooks.Add(misValue); 

      //~~> Set Sheet 1 as the sheet you want to work with 
      xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 

      //~~> Set your range 
      Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1]; 

      CR.Select(); 

      xlWorkSheet.Paste(CR, false); 

      // xlWorkBook.Close(true, misValue, misValue); 
      // xlexcel.Quit(); 

      // releaseObject(xlWorkSheet); 
      // releaseObject(xlWorkBook); 
      // releaseObject(xlexcel); 
     } 

     //private void releaseObject(object obj) 
     //{ 
     // try 
     // { 
     //  System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); 
     //  obj = null; 
     // } 
     // catch (Exception ex) 
     // { 
     //  obj = null; 
     //  MessageBox.Show("Unable to release the Object " + ex.ToString()); 
     // } 
     // finally 
     // { 
     //  GC.Collect(); 
     // } 
     //} 
    } 
} 

SNAPSHOT

enter image description here

관련 문제