<mySearch ⁄>
<mySnippets order="rand" ⁄>
<myContacts ⁄><email ⁄>
<windows live messenger ⁄>
<myCurriculum type="pdf" ⁄>
<myBlog show="last" ⁄>
<myNews show="rand" ⁄>
<myNews type="cat" ⁄>
<myQuote order="random" ⁄>Cair é do homem, levantar é de DEUS.
<myPhoto order="random" ⁄>
<myAdSense ⁄>
<myVisitorsMap ⁄>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Inserir Valores num Ficheiro Excel</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="lblResult" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string xlsFilename = Server.MapPath("~/teste/teste.xls"); string xlsSheetName = "MySheet"; ArrayList xlsFields = new ArrayList(); ArrayList xlsValues = new ArrayList(); //dummy data for update xlsFields.Add("nome"); xlsFields.Add("morada"); xlsFields.Add("telefone"); xlsValues.Add("http://www.pedrocorreia.net/mySnippets"); xlsValues.Add("Morada de Exemplo 1"); xlsValues.Add("98 765 43 21"); // try { Excel xls = new Excel(xlsFilename, xlsSheetName,"id","1", xlsValues, xlsFields); xls.ExcelUpdateRow(); lblResult.Text = "Ficheiro actualizado com sucesso"; } catch (Exception ex){ //nota: deverá ser feito outro tipo de tratamento ... lblResult.Text="Ocorreu o seguinte erro: " + (ex.Message.ToString()); } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.Text; using System.Collections; /// <summary> /// Class Excel /// </summary> public class Excel { private string _filename; private string _sheetName; private int _numFields; private ArrayList _fields; private ArrayList _values; private string _filterField; private string _filterValue; /// <summary> /// Método construtor (actualizar dados) /// </summary> /// <param name="filename">Nome do ficheiro</param> /// <param name="sheetName">Nome da Sheet (folha do excel)</param> /// <param name="filterField">Campo de Filtro</param> /// <param name="filterValue">Valor do campo de Filtro</param> /// <param name="values">Valores a inserir</param> /// <param name="fields">Nome das colunas que definem a estrutura</param> public Excel(string filename, string sheetName, string filterField, string filterValue, ArrayList values, ArrayList fields) { if (values.Count != fields.Count) { throw new Exception("O número de campos tem de coincidir com o número de valores"); } this._numFields = fields.Count; this._filename = filename; this._sheetName = sheetName; this._values = new ArrayList(); this._values = values; this._fields = new ArrayList(); this._fields = fields; this._filterField = filterField; this._filterValue = filterValue; } /// <summary> /// Actualizar valores no ficheiro Excel /// </summary> /// <returns>Estado da Operação</returns> public bool ExcelUpdateRow() { if (String.IsNullOrEmpty(this._filterField) || String.IsNullOrEmpty(this._filterValue)) { throw new Exception("FilterField and FilterValue required"); } bool result = true; StringBuilder sbFields_ValuesParams = new StringBuilder(); string iSQL, auxValor, auxCampo; //criar instrução sql for (int i = 0; i < this._numFields; i++) { auxCampo = this._fields[i].ToString(); sbFields_ValuesParams.Append(String.Format("{0}=@{0}", auxCampo)); //campos e parametros if (i < this._numFields - 1) { sbFields_ValuesParams.Append(", "); } } //construir instrução sql de update iSQL = String.Format("Update [{0}$] set {1} Where {2}=@{2}", this._sheetName, sbFields_ValuesParams.ToString(), this._filterField); // OleDbConnection myConnection = new OleDbConnection(this.ExcelConnection()); OleDbCommand myCommand = new OleDbCommand(iSQL, myConnection); try { for (int i = 0; i < this._numFields; i++) { //preencher valores auxCampo = this._fields[i].ToString(); auxValor = this._values[i].ToString(); myCommand.Parameters.Add(new OleDbParameter(String.Format("@{0}", auxCampo), auxValor)); } //parametro de restrição myCommand.Parameters.Add(new OleDbParameter(String.Format("@{0}", this._filterField), this._filterValue)); myConnection.Open(); myCommand.Connection = myConnection; myCommand.ExecuteNonQuery(); myConnection.Close(); } catch (Exception ex) { //tratar da excepção myCommand.Dispose(); myConnection.Close(); throw new Exception(ex.Message.ToString()); } return result; } /// <summary> /// Obter ConnectionString para ligação ao Excel /// </summary> /// <returns>ConnectionString</returns> private string ExcelConnection() { return @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + this._filename + @";Extended Properties=""Excel 8.0;HDR=Yes;"""; } }