使用EPPlus我希望水平加载数据。
var randomData = new[] { "Foo", "Bar", "Baz" }.ToList();
ws.Cells["B4"].LoadFromCollection(randomData);
默认行为是垂直的,此代码将导致:
这就是我需要的:
使用EPPlus的缺点是,他们documentation是粗略的。
答案 0 :(得分:2)
如果您做了类似的事情该怎么办:
var randomData = new[] { "Foo", "Bar", "Baz" }.ToList();
//ws.Cells["B4"].LoadFromCollection(randomData);
ws.Cells["B4"].LoadFromArrays(new List<string[]>(new[] { randomData.ToArray() }));
这在输出中给了我这个:
请记住,如果您关注性能,比如非常大的集合,那么最好还是编写自己的代码,因为LoadFrom*
方法确实会增加开销来解决多种情况。
答案 1 :(得分:1)
如果我被判自行循环,我可以编写代码:
public byte[] TestExcellGeneration_HorizontalLoadFromCollection()
{
byte[] result = null;
using (ExcelPackage pck = new ExcelPackage())
{
var foo = pck.Workbook.Worksheets.Add("Foo");
var randomData = new[] { "Foo", "Bar", "Baz" }.ToList();
//foo.Cells["B4"].LoadFromCollection(randomData);
int startColumn = 2; // "B";
int startRow = 4;
for(int i = 0; i < randomData.Count; i++)
{
foo.Cells[startRow, startColumn + i].Value = randomData[i];
}
result = pck.GetAsByteArray();
}
return result;
}
当你从TestMethod调用它时:
[TestMethod]
public void TestExcellGeneration_HorizontalLoadFromCollection()
{
var excelFileBytes = (new MyExcelGenerator()).TestExcellGeneration_HorizontalLoadFromCollection();
OpenExcelFromTempFile(excelFileBytes);
}
private void OpenExcelFromTempFile(byte[] data)
{
string tempPath = System.IO.Path.GetTempFileName();
System.IO.File.WriteAllBytes(tempPath, data);
Application excelApplication = new Application();
_Workbook excelWorkbook;
excelWorkbook = excelApplication.Workbooks.Open(tempPath);
excelApplication.Visible = true;
}
结果是:
答案 2 :(得分:0)
这是一个扩展方法:
public static void LoadFromCollectionHorizontally<T>(this ExcelWorksheet excelWorksheet, IEnumerable<T> objects, string cellAddress = "A1")
{
List<object[]> valuesHorizontally = new List<object[]>();
if (typeof(T).IsClass)
{
var properties = typeof(T)
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => !Attribute.IsDefined(p, typeof(EpplusIgnore)));
foreach (var prop in properties)
{
var values = new List<object>();
foreach (T item in objects)
{
values.Add(prop.GetValue(item));
}
valuesHorizontally.Add(values.ToArray());
}
}
else
{
valuesHorizontally.Add(objects.Cast<ValueType>().ToArray());
}
var startingCellRange = excelWorksheet.Cells[cellAddress];
var filledUpCellRange = startingCellRange.LoadFromArrays(valuesHorizontally);
...
}