我创建了一个将Excel文件导出到gridView并将其导入到word的项目。现在,我通过单击发送到ExportData()方法的每一行的ID来实现这一点。
现在我要实现的是,单击名为ImportALL的按钮,为gridView中的每一行创建单独的word文档。
例如,对于gridview中的每一行,我都想要类似
doc1.docx(包括gridview的第一行数据)
doc2.docx(包括gridview的第二行数据)
doc3.docx(包括gridview的第三行数据)
例如:
这是我的模特。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);
}
答案 0 :(得分:0)
文件读写操作将不允许其他进程使用。
workbook.Close(false, Type.Missing, Type.Missing);
application.Quit();
ViewBag.Docs = docs;
TempData["docs"] = docs;
return View("Success");
替换您的代码
Response.ClearContent();
Response.ContentType = "application/ms-word";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.doc", "WordFileName"));
Response.Charset = "";
System.IO.StringWriter stringwriter = new System.IO.StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
gv.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString());
Response.End();