gpt4 book ai didi

c# - 如何使用 EPPlus 设置 XLSX 单元格宽度?

转载 作者:IT王子 更新时间:2023-10-29 03:42:59 33 4
gpt4 key购买 nike

你好,我有这段代码,我在其中创建了一个 xlsx 文件,我需要预先设置 xlsx 工作表单元格的宽度。实际问题是,当我打开 excell 时,我需要用鼠标双击列之间的间隙,以便展开列并查看隐藏的数据。有没有办法通过 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);

最佳答案

我发现在填写工作表上的所有数据后设置列宽有效:

ws.Column(1).Width = 50;

还有 autoFitColumns 方法,但它会忽略带有公式和换行文本的单元格,因此它对我不起作用。

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

关于c# - 如何使用 EPPlus 设置 XLSX 单元格宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9096176/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com