2016-07-31 2 views
0

데이터를 내보낼 때 Excel 파일이 비어 있습니다! 초보자이며 문제를 해결할 수 없습니다.C#에서 Excel 데이터 내보내기 앱

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application(); 
     Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet); 
     Worksheet ws = (Worksheet)Excel.ActiveSheet; 
     Excel.Visible = true; 


     ws.Cells[1, 1] = "Row"; 
     ws.Cells[1, 2] = "نام"; 
     ws.Cells[1, 3] = "نام خانوادگی"; 
     ws.Cells[1, 4] = "تاریخ ورود"; 
     ws.Cells[1, 5] = "تاریخ خروج"; 
     ws.Cells[1, 6] = "زمان ورود"; 
     ws.Cells[1, 7] = "زمان خروج"; 
     ws.Cells[1, 8] = "تاریخ فارسی"; 


     for(int j=2;j<=dataGridView1.Rows.Count; j++) 
     { 
      for(int i=2;i<=5;i++) 
      { 
       ws.Cells[j, 1] = dataGridView1.Rows[j - 2].Cells[i - 1].Value; 
      } 
     } 

결과 : Current Excel snapshot

+2

워크 시트를 저장하고 닫는 코드가 누락되었습니다. –

+0

이것 좀보세요 : http://stackoverflow.com/questions/6840099/how-can-i-export-data-to-excel-file –

답변

0

파이 얌 Hayati 이 내 코드입니다! 파일이나 워크 시트를 저장하지 않았으므로 원하는 출력을 얻지 못했습니다. 예를 들어 아래를 참조하십시오.

public class Product 
{ 
    public string Code { get; set; } 
    public string Name { get; set; } 
    public double Price { get; set; } 
} 

위의 내용은 Excel 파일을 저장하거나 내보내는 방법을 보여주는 클래스입니다. 목록에 다음과 같이 이제 우리는 개체의 컬렉션을 만들 것이다 : 방법에 지금

List<Product> products = new List<Product>() 
{ 
    new Product { Code = "1234", Name = "Denim Jeans", Price = 2000 }, 
    new Product { Code = "123456", Name = "Denim Jacket", Price = 3000 }, 
    new Product { Code = "12345678", Name = "Nike Sneakers", Price = 4000 } 
}; 

, 다음 코드를 넣어 : ( Microsoft.Office.Interop.Excel.dll 의 참조를 추가해야합니다)

public void ExportToExcel(List<Product> products) 
{ 
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 

    excel.Workbooks.Add(); //Create empty workbook 
    Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet; //Create Worksheet from active sheet 

    try 
    { 
    workSheet.Cells[1, "A"] = "Code"; //Set the header 
    workSheet.Cells[1, "B"] = "Name"; 
    workSheet.Cells[1, "C"] = "Price"; 

    int row = 2; //Start the row 
    foreach (Product items in products) //Iterate through a loop 
    { 
     workSheet.Cells[row, "A"] = items.Code; 
     workSheet.Cells[row, "B"] = items.Name; 
     workSheet.Cells[row, "C"] = string.Format("{0} Price", items.Price); 

     row++; 
    } 

    workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1); 

    string fileName = string.Format(@"{0}\DatainExcel.xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); 

    workSheet.SaveAs(fileName); //Save data in the file 

    MessageBox.Show(string.Format("The file '{0}' is saved successfully!", fileName)); 
} 

catch (Exception exception) 
{ 
    MessageBox.Show("Exception", "Problem while saving Excel file!\n" + exception.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); 
} 

finally 
{ 
    excel.Quit(); //This is to quit excel 

    if (excel != null) 
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel); 

    if (workSheet != null) 

    System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet); 

    excel = null; 
    workSheet = null; 

    GC.Collect(); //This is to force garbage cleaning 
    } 
} 

그리고 끝났습니다. 한 번 해봐.

관련 문제