2009-10-07 12 views
1

Je veux créer un fichier Excel dire personinfo.xls avec une feuille de travail dire Personne.Comment créer un fichier Excel avec des feuilles en C#?

Y a-t-il un moyen en C# de le faire?

+0

Jetez un oeil à cet article MSDN [Comment: utiliser COM Interop pour créer une feuille de calcul Excel (Guide de programmation C#) ] (http: // msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx) – Joe

Répondre

2

Avez-vous essayé l'Interop Excel? Est-ce pour Excel 2003/2007? Si il est excel 2007 xml vous pouvez essayer

Carlos

SpreadsheetGear

ExcelPackage (Codeplex)

+0

+1 pour l'ExcelPackage (sur CodePLex) - excellent outil –

+0

+1 pour ExcelXmlWriter de Carlos. Fonctionne très bien. –

3

Vous pouvez le faire avec MyXLS.

Je l'ai utilisé dans quelques projets avec beaucoup de succès.

Son opensource.

2

Essayez cette classe:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.IO; 
using Excel = Microsoft.Office.Interop.Excel; 
using System.Reflection; 
using System.Threading; 
using System.Diagnostics; 
using System.Drawing; 
using System.Windows.Forms; 
using System.Xml; 
using System.Data.SqlClient; 

namespace ExcelDemo 
{ 
    static class ExcelImportExport 
    { 
     public static void ExportToExcel(string strFileName, string strSheetName) 
     { 
      // Run the garbage collector 
      GC.Collect(); 

      // Delete the file if it already exists 
      if (System.IO.File.Exists(strFileName)) 
      { 
       System.IO.File.SetAttributes(strFileName, FileAttributes.Normal); 
       System.IO.File.Delete(strFileName); 
      } 

      // Open an instance of excel. Create a new workbook. 
      // A workbook by default has three sheets, so if you just want a single one, delete sheet 2 and 3 
      Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 
      Excel._Workbook xlWB = (Excel._Workbook)xlApp.Workbooks.Add(Missing.Value); 
      Excel._Worksheet xlSheet = (Excel._Worksheet)xlWB.Sheets[1]; 
      ((Excel._Worksheet)xlWB.Sheets[2]).Delete(); 
      ((Excel._Worksheet)xlWB.Sheets[2]).Delete(); 

      xlSheet.Name = strSheetName; 
      // Write a value into A1 
      xlSheet.Cells[1, 1] = "Some value"; 

      // Tell Excel to save your spreadsheet 
      xlWB.SaveAs(strFileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); 
      xlApp.Quit(); 

      // Release the COM object, set the Excel variables to Null, and tell the Garbage Collector to do its thing 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet); 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWB); 
      System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); 

      xlSheet = null; 
      xlWB = null; 
      xlApp = null; 

      GC.Collect(); 

     } 


    } 

} 
+0

pourquoi les appels GC.Collect() ?? –

+0

Le dernier à la fin est parce que le garbage collector .NET ne sera pas nécessairement exécuté automatiquement lors de la suppression des objets COM; Par conséquent, si vous essayez d'appeler la fonction une deuxième fois, cela peut créer une nouvelle instance d'Excel. Le premier est là juste pour des fins de débogage - au cas où le code a échoué à mi-chemin de la dernière course, pour se débarrasser de tout reste Excels: 0) – ScottF

+0

Cela devrait être comme vous le faites, ne pas utiliser de tiers bibliothèques de parties. Les PIA sont vraiment faciles à utiliser, mais vous devez vous assurer de la libération à la fin voir http://support.microsoft.com/default.aspx?scid=kb;en-us;317109. –

0

fera avec le code suivant:

  // Create a new empty workbook with one worksheet. 
      IWorkbook workbook = Factory.GetWorkbook(); 
      // Get the worksheet and change it's name to "Person". 
      IWorksheet worksheet = workbook.Worksheets[0]; 
      worksheet.Name = "Person"; 
      // Put "Hello World!" into A1. 
      worksheet.Cells["A1"].Value = "Hello World!"; 
      // Save the workbook as xls (Excel 97-2003/Biff8). 
      workbook.SaveAs(@"C:\tmp\personinfo.xls", FileFormat.Excel8); 
      // Save the workbook as xlsx (Excel 2007 Open XML). 
      workbook.SaveAs(@"C:\tmp\personinfo.xlsx", FileFormat.OpenXMLWorkbook); 

Vous pouvez télécharger un essai gratuit here si vous voulez essayer vous-même.

Disclaimer: Je possède SpreadsheetGear LLC

1

Si vous avez besoin seulement d'être compatible avec Excel 2007 ou plus tard, je pencherais pour la OpenXML SDK.

Découvrez le dernier message de la première page de pour un exemple très basique. SpreadsheetML peut être assez déroutant au début, mais si vous devez générer des documents de bureau régulièrement, cela vaut vraiment la peine d'apprendre. Vous pouvez trouver des ressources sur openxmldeveloper.org

Cordialement
Oliver Hanappi

Questions connexes