gpt4 book ai didi

c# - 将动态标签文本导出到 Excel

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:54 25 4
gpt4 key购买 nike

我有一个小程序可以在 flowLayoutPanel1 中生成一些动态标签。我试图将这些标签的文本导出到 Excel,但我得到的只是最后一个标签的值。

这是我的导出类:

 class Export
{

public Export(bool defaultBackgroundIsWhite)
{
this.defaultBackgroundIsWhite = defaultBackgroundIsWhite;

app = new Application();
app.Visible = true;
workbook = app.Workbooks.Add(1);
worksheet = (Worksheet)workbook.Sheets[1];
}

public void Do(string excelName, System.Windows.Forms.Label names)
{
for (int i = 0; i <= 5; i++)
{
AddNames(i,0,names);
}
}

private void AddNames(int row, int col, System.Windows.Forms.Label lbls)
{
if (lbls == null) return;
row++;
col++;
Range range = worksheet.Cells[row + 2, col + 2];
range.NumberFormat = "";
worksheet.Cells[row + 2, col + 2] = lbls.Text;
row--;
col--;

}
private Application app = null;
private Workbook workbook = null;
private Worksheet worksheet = null;
private bool defaultBackgroundIsWhite;
}

表单类代码:

    public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
create();
}

Label lbl;
private void create()
{
flowLayoutPanel1.Controls.Clear();
//int length = ds.Tables[0].Rows.Count;
for (int i = 0; i < 5; i++)
{
lbl = new Label();
lbl.Name = i.ToString();
lbl.Text = "Label "+i;
lbl.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
lbl.SetBounds(0, 20, 100, 25);
lbl.BorderStyle = BorderStyle.FixedSingle;
flowLayoutPanel1.Controls.Add(lbl);
}
}

private void button1_Click(object sender, EventArgs e)
{
Export ep = new Export(true);
ep.Do("test.xsl", lbl);
}

我的结果:

enter image description here

最佳答案

您总是添加最后创建的标签的文本,因为您只是传递它的引用。您应该传递带有所有标签引用的列表,您希望将其文本属性导出到 Excel。更改这些方法:

    List<Label> lbls;
private void create()
{
flowLayoutPanel1.Controls.Clear();
//int length = ds.Tables[0].Rows.Count;
lbls = new List<Labels>();
for (int i = 0; i < 5; i++)
{
Label lbl = new Label();
lbl.Name = i.ToString();
lbl.Text = "Label "+i;
lbl.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Regular);
lbl.SetBounds(0, 20, 100, 25);
lbl.BorderStyle = BorderStyle.FixedSingle;
flowLayoutPanel1.Controls.Add(lbl);
lbls.Add(lbl);
}
}

同样改变方法DoExport类接受 List<Label>相反 Label :

    public void Do(string excelName, List<Label> names)
{
for (int i = 0; i <= names.Count; i++)
{
AddNames(i,0,names[i]);
}
}

关于c# - 将动态标签文本导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536482/

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