我昨天又开始学习编程了。作为一项任务,我制作了一个 API,可以在其中创建 Excel 文件,可以在其中填写文本框,并且此文本框中的文本将填充 excel 中的一个单元格。这是我为创建 excel 文件的任务所做的(问题出现在代码之后)。
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DownloadExcel(string field, int id = 0)
{
var bla = field;
List<Record> obj = new List<Record>();
obj = RecordInfo(field);
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
str.Append("<td><b><font face=Arial Narrow size=3>Fieldname</font></b></td>");
str.Append("</tr>");
foreach (Record val in obj)
{
str.Append("<tr>");
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + val.Fieldname.ToString() + "</font></td>");
str.Append("</tr>");
}
str.Append("</table>");
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Information" + DateTime.Now.Year.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] temp = System.Text.Encoding.UTF8.GetBytes(str.ToString());
return File(temp, "application/vnd.ms-excel");
}
public List<Record> RecordInfo(string fieldname = "test")
{
List<Record> recordobj = new List<Record>();
recordobj.Add(new Record { Fieldname = fieldname });
return recordobj;
}
}
现在我的问题是。是否可以通过 C# 修改 Excel 中的字段,是否可以使用文本框修改特定单元格,并且单击时数据将更改(例如,我想将单元格 D7 从 1 调整为 2,所以我转到我的表单并在文本框中填写 2 并按提交,当我打开 Excel 时,特定单元格将显示新数字)。我搜索了一下,但找不到答案。感谢如何制作的链接。
提前感谢!
我建议您切换到另一种方法并使用"成人"库来创建 excel 文件。EPPlus是免费的,提供了强大的功能并且非常易于使用。
看看例子: http://epplus.codeplex.com/wikipage?title=WebapplicationExample
有点晚了,但我前段时间回答了我自己的问题。对于那些感兴趣的人,这是我如何解决问题的代码。
public class ExcelModel
{
Application excelApp;
string newValue;
public ExcelModel(string newValue)
{
excelApp = new Application();
this.newValue = newValue;
}
public void openExcelSheet(string fileName)
{
Workbook workbook = excelApp.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet sheet = (Worksheet)workbook.Worksheets.get_Item(2);
double oldValue = sheet.get_Range("D6").get_Value();
sheet.Cells[6, 4] = newValue;
workbook.SaveAs("\Users\user1\Downloads\text3.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
excelApp.Visible = true;
Workbook newWorkbook = excelApp.Workbooks.Open("\Users\user1\Downloads\text3.xlsx");
}
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult UpdateExcel(string field, int id = 0)
{
ExcelModel model = new ExcelModel(field);
string file = "\Users\user1\Downloads\Testdocument.xlsx";
model.openExcelSheet(file);
return RedirectToAction("Index");
}
public List<Record> RecordInfo(string fieldname = "test")
{
List<Record> Recordobj = new List<Record>();
Recordobj.Add(new Record { Fieldname = fieldname });
return Recordobj;
}
}