2012-02-01 12 views
50

Ciao Ho questo codice dove creo un file xlsx e ho bisogno di preimpostare la larghezza delle celle del foglio xlsx. Il vero problema è che quando apro l'excell ho bisogno di fare doppio clic sullo spazio tra le colonne con il mouse per scartare le colonne e rivedere i dati che sono nascosti. C'è un modo per farlo programmaticamente con Epplus?Come impostare la larghezza della cella xlsx con EPPlus in C#

using (ExcelPackage p = new ExcelPackage()) 
      { 
       String filepath = "C://StatsYellowPages.csv"; 
       DataSet ds = ExportCSVFileToDataset(filepath, "tblCustomers", "\t"); 
       //Here setting some document properties    
       p.Workbook.Properties.Title = "StatsYellowPages"; 

       //Create a sheet 
       p.Workbook.Worksheets.Add("Sample WorkSheet"); 
       ExcelWorksheet ws = p.Workbook.Worksheets[1]; 
       ws.Name = "StatsYellowPages"; //Setting Sheet's name 

       //Merging cells and create a center heading for out table 
       ws.Cells[1, 1].Value = "StatsYellowPages"; 
       ws.Cells[1, 1, 1, ds.Tables[0].Columns.Count].Merge = true; 
       ws.Cells[1, 1, 1, ds.Tables[0].Columns.Count].Style.Font.Bold = true; 
       ws.Cells[1, 1, 1, ds.Tables[0].Columns.Count].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; 

       int colIndex = 1; 
       int rowIndex = 2; 

       foreach (DataColumn dc in ds.Tables[0].Columns) //Creating Headings 
       { 
        var cell = ws.Cells[rowIndex, colIndex]; 

        //Setting the background color of header cells to Gray 
        var fill = cell.Style.Fill; 
        fill.PatternType = ExcelFillStyle.Solid; 
        fill.BackgroundColor.SetColor(Color.Gray); 


        //Setting Top/left,right/bottom borders. 
        var border = cell.Style.Border; 
        border.Bottom.Style = ExcelBorderStyle.Thin; 
        border.Top.Style = ExcelBorderStyle.Thin; 
        border.Left.Style = ExcelBorderStyle.Thin; 
        border.Right.Style = ExcelBorderStyle.Thin; 

        //Setting Heading Value in cell 
        cell.Value = dc.ColumnName; 

        colIndex++; 
       } 

       foreach (DataRow dr in ds.Tables[0].Rows) // Adding Data into rows 
       { 
        colIndex = 1; 
        rowIndex++; 
        foreach (DataColumn dc in ds.Tables[0].Columns) 
        { 
         var cell = ws.Cells[rowIndex, colIndex]; 
         //Setting Value in cell 
         cell.Value = dr[dc.ColumnName].ToString(); 
         //Setting borders of cell 
         var border = cell.Style.Border;      
         colIndex++; 
        } 
       } 


       //Generate A File with Random name 
       Byte[] bin = p.GetAsByteArray(); 
       string file = "c:\\StatsYellowPages.xlsx"; 
       File.WriteAllBytes(file, bin); 

risposta

98

trovo che l'impostazione la larghezza delle colonne dopo aver compilato tutti i dati sul foglio funziona:

ws.Column(1).Width = 50; 

C'è anche il metodo autoFitColumns ma questo ignora le celle con le formule e avvolto testo in modo non ha funzionato per me.

ws.Cells["A1:K20"].AutoFitColumns(); 
+1

thanx, sembra funzionare ver bene . – themis

+6

Vorrei aggiungere che se si desidera autofit tutte le colonne di un foglio di lavoro, fare questo 'for (i = 1; i <= ws.Dimension.End.Column; i ++) { \t ws.Column (i) .AutoFit (); } – guanome

+2

funziona ma impostando un valore diverso, ad esempio voglio impostare la larghezza della colonna su 7.86 ma è impostato su 7.14 e per 3.5 è impostato su 2.71 –

18

risposta reale è già contrassegnato questo è il modo giusto di impostare la larghezza della colonna, ma c'è un problema che si ha quando il documento viene aperto per la prima volta in Excel, ricalcola Larghezza colonne (non so perché) così come ho già detto nel commento sotto la risposta contrassegnata quando imposto la larghezza della colonna a 7,86 la ripristina a 7,14 e da 10,43 a 9,7x.

ho trovato il codice seguente da this epp reported issue per ottenere la larghezza della colonna possibile armadio come desiderato.

//get 7.14 in excel 
ws.Column(1).Width = 7.86; 

//get 7.86 in excel 
ws.Column(1).Width = GetTrueColumnWidth(7.86); 

public static double GetTrueColumnWidth(double width) 
     { 
      //DEDUCE WHAT THE COLUMN WIDTH WOULD REALLY GET SET TO 
      double z = 1d; 
      if (width >= (1 + 2/3)) 
      { 
       z = Math.Round((Math.Round(7 * (width - 1/256), 0) - 5)/7, 2); 
      } 
      else 
      { 
       z = Math.Round((Math.Round(12 * (width - 1/256), 0) - Math.Round(5 * width, 0))/12, 2); 
      } 

      //HOW FAR OFF? (WILL BE LESS THAN 1) 
      double errorAmt = width - z; 

      //CALCULATE WHAT AMOUNT TO TACK ONTO THE ORIGINAL AMOUNT TO RESULT IN THE CLOSEST POSSIBLE SETTING 
      double adj = 0d; 
      if (width >= (1 + 2/3)) 
      { 
       adj = (Math.Round(7 * errorAmt - 7/256, 0))/7; 
      } 
      else 
      { 
       adj = ((Math.Round(12 * errorAmt - 12/256, 0))/12) + (2/12); 
      } 

      //RETURN A SCALED-VALUE THAT SHOULD RESULT IN THE NEAREST POSSIBLE VALUE TO THE TRUE DESIRED SETTING 
      if (z > 0) 
      { 
       return width + adj; 
      } 

      return 0d; 
     } 
2

La risposta di Mubashar Ahmad mi ha aiutato, grazie per questo. Volevo includere come l'ho usato nel mio progetto. L'ho trasformato in un metodo di estensione e l'ho refactored.

Ecco l'implementazione, che imposta la larghezza della cella per la prima colonna del foglio di lavoro.

worksheet.Column(1).SetTrueColumnWidth(28); 

Ecco il metodo di estensione per impostare una larghezza di colonna più preciso nel file EPPlus Excel, notare che questo metodo deve essere all'interno di una classe statica:

public static void SetTrueColumnWidth(this ExcelColumn column, double width) 
    { 
     // Deduce what the column width would really get set to. 
     var z = width >= (1 + 2/3) 
      ? Math.Round((Math.Round(7 * (width - 1/256), 0) - 5)/7, 2) 
      : Math.Round((Math.Round(12 * (width - 1/256), 0) - Math.Round(5 * width, 0))/12, 2); 

     // How far off? (will be less than 1) 
     var errorAmt = width - z; 

     // Calculate what amount to tack onto the original amount to result in the closest possible setting. 
     var adj = width >= 1 + 2/3 
      ? Math.Round(7 * errorAmt - 7/256, 0)/7 
      : Math.Round(12 * errorAmt - 12/256, 0)/12 + (2/12); 

     // Set width to a scaled-value that should result in the nearest possible value to the true desired setting. 
     if (z > 0) 
     { 
      column.Width = width + adj; 
      return; 
     } 

     column.Width = 0d; 
    } 
Problemi correlati