EXCEL导出,列表宽度大于内容列

摘要:
=0){sheetNum++;sheet=workbook.CreateSheet;}#region列头及样式{IRowheaderRow=sheet.CreateRow;ICellStyleheadStyle=workbook.CreateCellStyle();headStyle.Alignment=HorizontalAlignment.Center;//IFontfont=workbook.CreateFont();//font.FontHeightInPoints=10;//font.Boldweight=700;//headStyle.SetFont;for{headerRow.CreateCell.SetCellValue;headerRow.GetCell.CellStyle=headStyle;}}#endregionrowIndex=1;}#endregion#region填充内容varentity=item.GetType();PropertyInfo[]piList=entity.GetProperties();IRowdataRow=sheet.CreateRow;for{ICellnewCell=dataRow.CreateCell;stringdrValue=piList[i].GetValue==null?

//TIPS:列宽设置在最后

public static string Export<T>(string rootPath, List<T> list, string fileName, IDictionary<string, string> header, Action<int, string, string, XSSFWorkbook, ICell> action = null)
{
string relidateDict = "\Excel\" + DateTime.Now.ToString("yyyyMM") + "\";

string rootDict = rootPath.TrimEnd('\') + relidateDict;
rootDict = rootDict.Replace("%20", " ");

if (!System.IO.Directory.Exists(rootDict))
{
System.IO.Directory.CreateDirectory(rootDict);
}
string fileFullName = fileName + "_" + Guid.NewGuid().ToString("N") + ".xlsx";
var absolutePath = rootDict + fileFullName;
var workbook = ExportToWorkbook(list, header, action);
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
using (FileStream fs = new FileStream(absolutePath, FileMode.Create, FileAccess.ReadWrite))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}

}
var webPath = (relidateDict + fileFullName).Replace("\", "/");
return webPath;
}

/// <summary>
/// list导出到Excel的MemoryStream
/// </summary>
/// <param name="list">源数据</param>
/// <param name="strSheetName">工作表名称</param>
private static XSSFWorkbook ExportToWorkbook<T>(List<T> list, IDictionary<string, string> header, Action<int, string, string, XSSFWorkbook, ICell> action = null)
{
string[] oldColumnNames = header.Keys.ToArray();
string[] newColumnNames = header.Values.ToArray();

XSSFWorkbook workbook = new XSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
int sheetNum = 1;
int[,] arrWidth = new int[list.Count, oldColumnNames.Length];

int rowIndex = 0;
foreach (var item in list)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheetNum++;
sheet = workbook.CreateSheet("Sheet" + sheetNum.ToString());
}

#region 列头及样式
{
IRow headerRow = sheet.CreateRow(0);

ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
//IFont font = workbook.CreateFont();
//font.FontHeightInPoints = 10;
//font.Boldweight = 700;
//headStyle.SetFont(font);

for (int i = 0; i < oldColumnNames.Length; i++)
{
headerRow.CreateCell(i).SetCellValue(newColumnNames[i]);
headerRow.GetCell(i).CellStyle = headStyle;
}
}
#endregion

rowIndex = 1;
}
#endregion

#region 填充内容

var entity = item.GetType();
PropertyInfo[] piList = entity.GetProperties();

IRow dataRow = sheet.CreateRow(rowIndex);

for (int i = 0; i < piList.Length; i++)
{
ICell newCell = dataRow.CreateCell(i);

string drValue = piList[i].GetValue(item) == null ? "" : piList[i].GetValue(item).ToString();
arrWidth[rowIndex - 1, i] = Encoding.GetEncoding(936).GetBytes(drValue).Length;

string drType = piList[i].GetValue(item) == null ? "System.String" : piList[i].GetValue(item).GetType().ToString();
switch (drType)
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}

action?.Invoke(rowIndex, oldColumnNames[i], drValue, workbook, newCell);
}

#endregion

rowIndex++;
}
//设置列宽 (table数据源设置相同)
for (int i = 0; i < oldColumnNames.Length; i++)
{
int tmpWidth = Encoding.GetEncoding(936).GetBytes(newColumnNames[i]).Length;
for (int j = 0; j < list.Count - 1; j++)
{
if (arrWidth[j, i] > tmpWidth)
{
tmpWidth = arrWidth[j, i];
}
}
sheet.SetColumnWidth(i, (tmpWidth + 1) * 256);
}

return workbook;

}

免责声明:文章转载自《EXCEL导出,列表宽度大于内容列》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇简单的多线程通信实例(用委托事件实现)51单片机串口通信的注记下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

imagepicker插件的使用方法和选择按钮汉化

1,使用cordova-plugin-image-picker插件。 1 cordova plugin add https://github.com/wymsee/cordova-imagePicker.git 2,在相应的controller里添加方法。 我这里是写在一个util中,调用即可。 1 //图片选择 2 image...

Spring MVC + Mongodb

在maven的pom.xml中增加引用: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/...

把一个json字符串转换成对应的c#类型

放弃使用Newtonsoft,自己动手。usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Reflection; usingSystem.Text.RegularExpressions; namespaceConsol...

delphi TreeView 从数据库添加节点的四种方法

方法一:delphi中递归算法构建treeView 过程:通过读取数据库中table1的数据,来构建一颗树。table1有两个字段:ID,preID,即当前结点标志和父结点标志。所以整个树的表示为父母表示法。本递归算法不难写,但是要注意:程序内部的变量都应使用局部变量!比如当Query是外部变量(函数外定义或者直接通过控件拖拽得来)时就会得到错误的结果。代...

RocketMQ 参数详解

    NameServer配置属性 参数名 参数类型 描述 默认参数(时间为单位ms,数据单位为byte) rocketmqHome String RockerMQ主目录,默认用户主目录   namesrvAddr String NameServer地址   kvConfigPath String kv配置文件路径,包含顺序...

DevExpress WinForm MVVM数据和属性绑定指南(Part 1)

根据您绑定的属性,存在以下三种可能的情况: 常规绑定- ViewModel属性绑定到任何不可编辑的View元素属性。由于该元素不可编辑,因此您无需将更新通知发送回绑定属性(单向绑定)。 数据绑定- Model属性(数据字段)绑定到编辑器属性。如果用户可以更改编辑器值,则需要更新绑定属性(双向绑定)。 属性依赖- 来自同一个ViewModel的两个属性被绑...