【发布时间】:2019-03-19 21:17:57
【问题描述】:
我创建了一个将 excel 文件导出到 gridView 并将其导入到 word 的项目。现在我通过单击发送到 ExportData() 方法的每一行的 id 来实现这一点。
现在我想要实现的是,通过单击一个名为 ImportALL 的按钮,为 gridView 中的每一行创建单独的 word 文档。
例如,对于 gridview 中的每一行,我想要类似的东西
doc1.docx(包括gridview的第一行数据)
doc2.docx(包括gridview的第二行数据)
doc3.docx(包括gridview的第三行数据)
例如:
这是我的model.cs
public class Doc
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Quantity { get; set; }
public string PriceWord { get; set; }
}
这是我的阅读导出 excel 数据控制器
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content/" + excelFile.FileName);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
excelFile.SaveAs(path);
ExcelDoc.Application application = new ExcelDoc.Application();
ExcelDoc.Workbook workbook = application.Workbooks.Open(path);
ExcelDoc.Worksheet worksheet = workbook.ActiveSheet;
ExcelDoc.Range range = worksheet.UsedRange;
List<Doc> docs = new List<Doc>();
for (int row = 2; row < range.Rows.Count; row++)
{
Doc d = new Doc();
d.Id = Int32.Parse(((ExcelDoc.Range)range.Cells[row, 1]).Text);
d.Name = ((ExcelDoc.Range)range.Cells[row, 2]).Text;
d.Price = Decimal.Parse((((ExcelDoc.Range)range.Cells[row, 3]).Text));
d.PriceWord = numberToWordConverter(s.Price.ToString());
d.Quantity = ((ExcelDoc.Range)range.Cells[row, 4]).Text;
docs.Add(d);
}
ViewBag.Docs = docs;
TempData["docs"] = docs;
return View("Success");
}
else
{
ViewBag.Error = "File type is incorrect";
return View("Index");
}
这里是单词导出方法。
public ActionResult ExportData(int? id)
{
var docs = TempData["Docs"] as List<Doc>;
GridView gv = new GridView();
gv.DataSource = docs.Where(x=> x.Id == id);
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=dosya.doc");
Response.ContentType = "application/vnd.ms-word ";
Response.Charset = string.Empty;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
}
另外,我对以下部分有疑问。除非我在任务管理器中停止执行 Excel 文件,否则我会出现“无法访问,因为它被另一个进程使用”之类的错误
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
【问题讨论】:
标签: c# excel gridview import export