真没想到发个文章,格式这么难
BetweenWfile是待保存数据,
fileName是待保存文件路径
有借鉴别人动态改变单元格宽度,但是记不清是借鉴的哪位大佬的了
#region 保存、读取以及输出excel文件
/// <summary>
/// 保存excel并输出
/// </summary>
/// <param name="writefile"></param>
public void inputFileView(ArrayList BetweenWfile, string fileName)
{
string[] FinalWfile;
//创建工作薄
HSSFWorkbook wk = new HSSFWorkbook();
//创建一个名称为scoringSheet的表
ISheet score = wk.CreateSheet("scoringSheet");
IRow row = score.CreateRow(0);
//创建数据后
for (int i = 0; i < BetweenWfile.Count; i++)
{
int x = i + 2;
row = score.CreateRow(x);
FinalWfile = BetweenWfile[i].ToString().Split(Environment.NewLine.ToCharArray());
for (int j = 0; j < FinalWfile.Count() && j < 255; j++)
{
ICell cell = row.CreateCell(j);//在第X行中创建单元格
cell.SetCellValue(FinalWfile[j]);//循环往第X行的单元格中添加数据
}
}
int columnWidth = score.GetColumnWidth(0) / 256;//获取当前列宽度
for (int rowNum = 2; rowNum <= score.LastRowNum; rowNum++)//在这一列上循环行
{
IRow currentRow = score.GetRow(rowNum);
ICell currentCell = currentRow.GetCell(1);
if (currentRow.GetCell(0) != null) { currentCell = currentRow.GetCell(0); }
int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
if (columnWidth < length)
{
columnWidth = length;
}//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度,后面的+1是我人为的将宽度增加一个字符
}
score.SetColumnWidth(0, columnWidth * 180);
//}
using (FileStream fs = File.OpenWrite(fileName + @"\" + "scorexls.xls")) //打开一个xls文件,如果没有则自行创建,如果存在scorexls.xls文件则在创建是不要打开该文件!
{
wk.Write(fs); //向打开的这个xls文件中写入mySheet表并保存。
}
}