我正在编写一个使用DocumentFormat.OpenXml 2.5.0库的c#代码来读取excel文件中的值。 excel有三列。我的程序需要读取三列值并将值存储在List集合中,返回IEnumerable<ShipViewModel>
My View模型基本上包含三个属性。见下面的代码
public class ShipViewModel
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
}
阅读excel文件的逻辑
public List<ShipViewModel> OpenSpreadsheetDocument(string filepath)
{
List<ShipViewModel> model = new List<ShipViewModel>();
// Open a SpreadsheetDocument based on a filepath.
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filepath, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
string text;
foreach (Row r in sheetData.Elements<Row>())
{
foreach (Cell c in r.Elements<Cell>())
{
text = c.CellValue.Text;
Console.Write(text + " ");
}
}
}
}
我正在考虑填充for循环中的列表。请参阅下面的代码。 但是如果你检查上面的循环,Column2和Column3将包含Column1的相同单元格值,这不应该是大小写。单元格的值仅在下一次迭代期间更改。
ShipViewModel shipViewModel = new ShipViewModel();
shipViewModel.Column1 = c.CellValue.Text;
shipViewModel.Column2 = c.CellValue.Text;
shipViewModel.Column3 = c.CellValue.Text;
model.Add(shipViewModel);
答案 0 :(得分:0)
我可以向您展示如何将数据从Excel导入数据库,您必须从nuget安装LinqToExcel。 这是代码:
[HttpPost]
public JsonResult UploadExcel(Item items, HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = Server.MapPath("~/Content/Uploads/Excel/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var artistAlbums = from a in excelFile.Worksheet<Item>(sheetName) select a;
foreach (var a in artistAlbums)
{
try
{
if (a.Name != "" && a.Description != "" && a.Number != "")
{
Item TU = new Item();
TU.Name = a.Name;
TU.Description = a.Description;
TU.Number = a.Number;
db.Items.Add(TU);
db.SaveChanges();
}
else
{
data.Add("<ul>");
if (a.Name == "" || a.Name == null) data.Add("<li> Name is required</li>");
if (a.Description == "" || a.Description == null) data.Add("<li> Description is required</li>");
if (a.Number == "" || a.Number == null) data.Add("<li>Number is required</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("<ul>");
data.Add("<li>Only Excel file format is allowed</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data.Add("<ul>");
if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}