我正在使用带有EPPlus
扩展名的.xlsx
生成的Excel工作表编写一个列表。然后使用worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
方法尝试拟合列。
这是我写数据的方式
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
System.Data.DataTable dt = new System.Data.DataTable();
var ws = xlPackage.Workbook.Worksheets.FirstOrDefault(x => x.Name == language.Culture);
if (ws == null)
{
int i = 1, j = 0;
worksheet = xlPackage.Workbook.Worksheets.Add(language.Culture);
foreach (ExcelFields fieldValues in UnmatchedFieldList)
{
//code
}
else
{
int i = 0;
worksheet = xlPackage.Workbook.Worksheets[language.Culture];
colCount = worksheet.Dimension.End.Column;
rowCount = worksheet.Dimension.End.Row;
foreach (ExcelFields fieldValues in UnmatchedFieldList)
{
worksheet.Cells[rowCount + 1, count + 1].Value = itemName;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
xlPackage.Save();
}
我将数据读作
string sheetName = language.Culture;
var excelFile = new ExcelQueryFactory(excelPath);
IQueryable<Row> excelSheetValues = from workingSheet in excelFile.Worksheet(sheetName) select workingSheet;
string[] headerRow = excelFile.GetColumnNames(sheetName).ToArray();
在headerRow,它抛出以下错误
当我尝试从excel读取数据时,它会抛出异常
外部表格不是预期的格式
我发现,这是由于列没有正确格式化(宽度)。当我通过双击单元格手动设置列宽并运行代码时,它正常工作
所以我想用代码
来实现这个目标答案 0 :(得分:0)
由于连接字符串异常,外部表格不符合预期的格式异常,因此请使用以下示例检查您的连接字符串
public static string docPath= @"C:\sourcefolder\myfile.xlsx";
public static string ConnectionString= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + docPath + ";Extended Properties=Excel 12.0;";
或者如果您使用LinqToExcel,请检查您是否设置了DatabaseEngine属性,如下所示
public string docPath= @"C:\sourcefolder\myfile.xlsx";
var excelFile = new ExcelQueryFactory(docPath);
excelFile.DatabaseEngine = DatabaseEngine.Ace;