调用package.Save()
时出现以下错误:
表格1列类型没有唯一名称
我给表提供了一个名称,确保任何空单元格都有一个默认的空类型,但仍然无法找到出错的地方或如何设置不唯一的列类型名称。 这是我使用的代码:
public static bool ConvertToXlsx(string csvFilePath)
{
bool success = false;
//we need an xlsx file path for the export and need to ensure the passed in file path is a CSV one
var xlsxFilePath = Path.ChangeExtension(csvFilePath, "xlsx");
csvFilePath = Path.ChangeExtension(csvFilePath, "csv");
//convert the csv
if (!string.IsNullOrWhiteSpace(xlsxFilePath) && !string.IsNullOrWhiteSpace(csvFilePath))
{
try
{
using (ExcelPackage package = new ExcelPackage(new FileInfo(xlsxFilePath)))
{
//add a/another worksheet with datetime value so it doesn't clash with existing worksheets to the document
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Export_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss"));
//starting from cell A1, load in the CSV file data with first row as the header
worksheet.Cells["A1"].LoadFromText(
new FileInfo(csvFilePath), new ExcelTextFormat
{
Delimiter = ','
}, OfficeOpenXml.Table.TableStyles.Light1, true);
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
foreach (var cell in worksheet.Cells)
{
if (cell.Value == null)
{
cell.Value = "";
}
}
//save as xlsx
package.Save();
success = true;
}
//attempt to delete the previously generated CSV file
File.Delete(csvFilePath);
}
catch (Exception ex)
{
//if we cant delete the origionaly generated CSV file (used for the conversion), then return true
if (ex.Message.Contains($"Access to the path '{csvFilePath}' is denied."))
{
return true;
}
Console.WriteLine("Error: " + ex.Message);
return false;
}
}
return success;
}
答案 0 :(得分:3)
错误信息有点不清楚:它实际上是在说"The Table 'Table1', Column 'Type' does not have a unique name"
。请参阅here会发生什么。
LoadFromText将激发您在工作表中创建一个Table,它被称为“Table1”。你说“我给了桌子一个名字”,我说你没有。 EPPlus将表命名为“Table1”。 It happens here。您命名了工作表,该表已自动命名。
检查源csv的第一行,它可能不止一次包含单词“Type”。您可能希望在传递给epplus(检查重复项)之前稍微修改其内容,或在导入文本时检查not using the first line as a header的其他一些重载。
答案 1 :(得分:0)
我遇到了同样的问题,并解决了如下问题
public class ProductModel
{
[DisplayName("Name")]
public string ProductName {get; set;}
[DisplayName("Price")]
public decimal Price {get; set;}
[DisplayName("Price")]
public string Category {get ;set;}
}
[DisplayName(“ Price”)]->重复