从 Excel 导出并逐行导入到 Word asp.net mvc



我创建了一个项目,该项目将 excel 文件导出到 gridView 并将其导入 word。现在,我通过单击发送到 ExportData(( 方法的每一行的 id 来实现这一点。

现在我想要实现的是,通过单击一个名为 ImportALL 的按钮,为 gridView 中的每一行创建单独的 Word 文档。

例如,对于网格视图中的每一行,我都想有类似的东西

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);
}

如果在操作结束时未关闭文件读写操作,则不允许其他进程使用文件读写操作。

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();

最新更新