c# - 通过 asp.net 应用程序将值插入 excel
问题描述
我有一个电子表格需要接受来自 asp.net 应用程序的数据。
我写了一些 c#,允许我从另一个电子表格中读取数据,但现在我想从文本框中输入一些数据。
protected void Button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
string path = Server.MapPath("LOG_TEST.xlsx");
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;IMEX=1;'";
conn.ConnectionString = connString;
conn.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO [Sheet1$] ([NAME], [MOBILE], [EMAIL]) VALUES('" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "')",conn);
OleDbDataReader rd = cmd.ExecuteReader();
conn.Close();
}
只需将 3 个值插入电子表格即可。
我得到的错误如下。
我相信问题就在身边
OleDbDataReader rd = cmd.ExecuteReader();
但不确定用什么替换它。
解决方案
我建议像下面那样简化它:使用本地驱动器 C: 中的电子表格,更新connString
. 在您的 INSERT QUERY 中使用字符串值,您可以稍后对其进行更新。我们只是想确保它首先起作用!顺便说一句,我没有测试这段代码,但我认为它应该可以工作。
protected void Button2_Click(object sender, EventArgs e)
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\SPECIFY HERE\\LOG_TEST.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\"";
string query ="INSERT INTO [Sheet1$] (NAME, Mobile, Emails) VALUES ('Bob', '1', 'Whatever@mail')";
OleDbConnection con = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
我假设您可以编写一个函数来打开您的 excel 文件,例如
//Make sure you add these two references.
using Microsoft.Office.Interop
using Excel = Microsoft.Office.Interop.Excel
//Call this before your insert
static void FileOpen() {
string path = "Path.xlsx"
var excel = new Excel.Application
excel.Visible=True
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook sheet = books.Open(path);
}
推荐阅读
- javascript - Echarts - 从工具提示中排除系列
- node.js - 提交登录表单时无法对未安装的组件执行 React 状态更新
- javascript - 需要 Node js Query 来删除 Mongodb 中的重复项
- bash - 云外壳终端中的 gcp bash 脚本
- bash - How to execute WSL command with preloaded ".bash_aliases" from powershell
- java - How to terminate Camunda running process?
- three.js - 使用单个 AnimationClip 从网格(GLTF/FBX)管理动画
- python - TensorFlow 2.5 Mac M1 - 安装与 NumPy 库/Conda env 的兼容性问题
- express - 我的获取请求出现问题,请求正文变为空
- unit-testing - 有没有办法让等于(==)检查 kotlin.js.Date 对象工作?