88

こんにちは、xlsx ファイルを作成するこのコードがあり、xlsx シート セルの幅を事前に設定する必要があります。実際の問題は、エクセルを開くときに、列をアンラップして非表示のデータを表示するために、列間のギャップをマウスでダブルクリックする必要があることです。Epplus を使用してプログラムでこれを行う方法はありますか?

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);
4

5 に答える 5

160

シートにすべてのデータを入力した後に列幅を設定すると、次のように機能することがわかりました。

ws.Column(1).Width = 50;

autoFitColumns メソッドもありますが、これは数式と折り返されたテキストを含むセルを無視するため、うまくいきませんでした。

ws.Cells["A1:K20"].AutoFitColumns();
于 2012-02-02T14:37:42.363 に答える
30

実際の回答は、列幅を設定する正しい方法であると既にマークされていますが、Excel でドキュメントを初めて開いたときに、列の幅を再計算する (理由がわからない) という問題が 1 つあります。列幅を 7.86 に設定すると、7.14 にリセットされ、10.43 から 9.7x にリセットされます。

この epp 報告された問題から次のコードを見つけて、必要に応じてクローゼットの可能な列幅を取得しました。

//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;
        }
于 2013-07-28T08:34:14.223 に答える
10

Mubashar Ahmad の回答が役に立ちました。ありがとうございます。プロジェクトでどのように使用したかを含めたいと思いました。拡張メソッドにしてリファクタリングしました。

ワークシートの最初の列のセル幅を設定する実装を次に示します。

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

EPPlus Excel ファイルでより正確な列幅を設定するための拡張メソッドを次に示します。このメソッドは静的クラス内にある必要があることに注意してください。

    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;
    }
于 2017-05-09T16:12:30.437 に答える
2

DefaultColWidthプロパティを変更するだけで、ワークシートのすべての列のデフォルト幅を変更できます。

worksheet.DefaultColWidth = 25;
于 2020-01-21T12:38:10.870 に答える
1

もっと簡単な方法があります。Excel は、渡された列幅を量子化し、1 より下の 12 分の 1 と上の 7 分の 1 に表示します。これは階段状の結果を意味し、多くの最終値を作成できません (例: 3.5、4.5 など)。

幅を事前補正するには、以下で十分です。

IF DesiredWidth < 1 の場合

調整幅 = 12/7 * 希望の幅

そうしないと

調整幅 = 希望の幅 + 5/7

ENDIF

EPPLUSでWorksheet.Column(i).Width = AdjustedWidthと書く

これは単調な調整であり、Excel は開く/保存するときにすべての量子化を行います。

于 2020-10-30T00:35:07.090 に答える