//设置Excel的基本格式信息
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[];
Style styleHeader = workbook.Styles[workbook.Styles.Add()];
styleHeader.Font.Size = ;
styleHeader.HorizontalAlignment = TextAlignmentType.Center;
Style stylePowerInfo = workbook.Styles[workbook.Styles.Add()];
stylePowerInfo.IsTextWrapped = true;
Style styleTextCenter = workbook.Styles[workbook.Styles.Add()];
styleTextCenter.HorizontalAlignment = TextAlignmentType.Center;
Style styleTitle = workbook.Styles[workbook.Styles.Add()];
styleTitle.Font.IsBold = true;
styleTitle.Font.Size = ;
styleTitle.HorizontalAlignment = TextAlignmentType.Center;
styleTitle.ForegroundColor = Color.LightGreen;
//设置标题
worksheet.Cells[, ].Value = "本类别资料";
worksheet.Cells.Merge(, , , );
worksheet.Cells[, ].SetStyle(styleTitle);
worksheet.Cells[, ].Value = "名称";
worksheet.Cells[, ].SetStyle(styleTitle);
worksheet.Cells[, ].Value = "代号";
worksheet.Cells[, ].SetStyle(styleTitle);
//i+2表示从去掉总标题和子标题以后开始导出
for (int i = ; i < Convert.ToInt32(param[]); i++)
{
try
{
if (this.InvokeRequired)
{ worksheet.Cells[i + , ].PutValue(GetListText(i, ));
worksheet.Cells[i + , ].SetStyle(styleTextCenter);
worksheet.Cells[i + , ].PutValue(GetListText(i, ));
worksheet.Cells[i + , ].SetStyle(styleTextCenter);
}
else
{
worksheet.Cells[i + , ].PutValue(this.listView.Items[i].SubItems[].Text);
worksheet.Cells[i + , ].SetStyle(styleTextCenter);
worksheet.Cells[i + , ].PutValue(this.listView.Items[i].SubItems[].Text);
worksheet.Cells[i + , ].SetStyle(styleTextCenter);
}
if (progressBarX1.InvokeRequired)
{
progressBarX1.Invoke(new Action<int>(s => { this.progressBarX1.Value = s; }), i);
}
else
{
this.progressBarX1.Value = i;
}
if (lbState.InvokeRequired)
{
lbState.Invoke(new Action<string>(s => { this.lbState.Text = s; }), "当前执行第" + i + "条数据/共" + (this.listView.Items.Count - ).ToString() + "条数据,请等待..."); }
else
{
this.lbState.Text = "当前执行第" + i + "条数据/共" + (this.listView.Items.Count - ).ToString() + "条数据,请等待...";
} }
catch (Exception ex)
{
isSuccessful = false;
WriteLog(ex, "数据异常", false);
continue;
}
}
//设置列的宽度
worksheet.Cells.SetColumnWidthPixel(, );
worksheet.Cells.SetColumnWidthPixel(, );
workbook.Save(FileFullName);
//合并单元格
worksheet.Cells.Merge(rowIndex - userRowSpan, , userRowSpan, );
以上以从listview导出数据到excel为例