views:

363

answers:

0
StringBuilder sbExcelFileConnStr = new StringBuilder();
            sbExcelFileConnStr.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=");
            sbExcelFileConnStr.Append(sFile);
            sbExcelFileConnStr.Append(";Extended Properties=\"Excel 8.0;HDR=No;\"");

OleDbConnection xlConn = new OleDbConnection(sbExcelFileConnStr.ToString());
OleDbCommand cmd = new OleDbCommand();

xlConn.Open();
string updateSql = "UPDATE [" + wsName + "A2:F2] " +
                        "SET F1 = ?, F2 = ?, F3 = ?, F6 = ? ";

// Generate the UpdateCommand and add the parameters for the command.
cmd = new OleDbCommand(updateSql, xlConn);
cmd.Parameters.Add("@F1", OleDbType.Integer);
cmd.Parameters.Add("@F2", OleDbType.Integer);
cmd.Parameters.Add("@F3", OleDbType.Integer);
cmd.Parameters.Add("@F6", OleDbType.VarChar);

cmd.Parameters["@F1"].Value = pwy.Year;
cmd.Parameters["@F2"].Value = pwy.Period;
cmd.Parameters["@F3"].Value = pwy.Week;
cmd.Parameters["@F6"].Value = "p" + pwy.Period + "w" + pwy.Week + "y" + pwy.Year;

cmd.Connection = xlConn;
int affected = cmd.ExecuteNonQuery();

I'm updating an Excel template file using OleDB in a C# ASP.Net application. The problem is, some cells in the template have formatting (ie background color, text alignment). This formatting is completely removed if I update the value of the cell. The integer fields work fine, keeping the formatting, but the text field removes it

I know there are a lot questions on here about similar topics so let me clear a few things up

  • I can connect to the file and update it until my heart's content
  • I'm in a server environment, so using Interop is out of the question
  • I'm aware of third party solutions, but they are $$$
  • The client only uses Excel 2003, so OpenXML is out of the question