你最好是将插入的数据写入到dataset,或者datatable中,然后再写入excel
在sheet1中包含一个列表,有表头c1,c2,c3,即a1单元格的值是c1,a2单元格的值是c2,a1单元格的值是c3。现需要往这个列表中插入一条数据:
string excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName+ ";Extended Properties=\"Excel 8.0;\"";
OleDbConnection conn = new OleDbConnection(excelConnectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
string sql = "insert into [sheet1$] values('1','2','3')";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
这是一种方法,当然也可以通过调用EXCEL的COM对象来完成。
如果你要插入的不是列表的话,如果你的excel中不是列表的话,需要在你sheet中特定的单元格中“插入名称”。
提供一个方法仅供参考哦
public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath)
{
Microsoft.Office.Interop.Excel.Application app =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
app.Visible = false;
Workbook wBook = app.Workbooks.Add(true);
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
if (excelTable.Rows.Count > 0)
{
int row = 0;
row = excelTable.Rows.Count;
int col = excelTable.Columns.Count;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
string str = excelTable.Rows[i][j].ToString();
wSheet.Cells[i + 2, j + 1] = str;
}
}
}
int size = excelTable.Columns.Count;
for (int i = 0; i < size; i++)
{
wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName;
}
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
//保存工作簿
wBook.Save();
//保存excel文件
app.Save(filePath);
app.SaveWorkspace(filePath);
app.Quit();
app = null;
return true;
}
catch (Exception err)
{
MessageBox.Show("导出Excel出错!错误原因:" + err.Message, "提示信息",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
finally
{
}
}
直接写文本,中间用tab分割,再用excel打开。
按行读取文件会吗?循环语句会写吗?