导出HTML表格到Excel,并格式化Excel文件

时间:2022-09-25 09:56:42

I have the following code:

我有以下代码:

<tfoot>
<tr>
  <td>Tot</td>
  <td>60</td>
  <td></td>
  <td>30</td>
</tr>
<tr>
   <td>Avg</td>
   <td>20</td>
   <td></td>
   <td>10</td>
</tr>

Code Behind:

背后的代码:

public string getWhileLoopData() 
{
 string htmlStr = "";
 SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
 SqlCommand thisCommand = thisConnection.CreateCommand();
 thisCommand.CommandText = "SELECT * FROM MyTable WHERE TheDate = @TheDate";
 thisCommand.Parameters.AddWithValue("@TheDate", txtDate.Text);


int totnum1 = 0;
decimal totnum2 = 0;
int numRow = 0;
decimal avg1 = 0;
decimal avg2 = 0;



 thisConnection.Open();
 SqlDataReader reader = thisCommand.ExecuteReader();

 while (reader.Read()) {
     int id = reader.GetInt32(0);

     int Number01 = reader.GetInt32(1);
     DateTime TheDate = reader.GetDateTime(2);
     Decimal Number02 = reader.GetDecimal(3);

     totnum1 += reader.GetInt32(1);
     totnum2 += reader.GetInt32(3);
     numRow ++;

     //string Pass = reader.GetString(2);
     htmlStr += "<tr><td>" + id + "</td><td>" + Number01 + "</td><td>" + TheDate + "</td><td>" + Number02 + "</td></tr>";
 }

 thisConnection.Close();

avg1 = totnum1 / numRow;
avg2 = totnum2 / numRow;

htmlStr += string.Format("<tfoot><tr><td>Tot</td><td>{0}</td><td></td><td>{1}</td></tr>", totnum1 , totnum2 );
htmlStr += string.Format("<tfoot><tr><td>Avg</td><td>{0}</td><td></td><td>{1}</td></tr></tfoot>", avg1 , avg2 );


 return htmlStr;
}

Does anyone know how to export it to an Excel file? But I want the excel file formatted. i.e.: Put an image on the Excel file after it is exported, font size, color, fill color, etc. All formatting needs to be done from code behind.

有人知道如何将它导出到Excel文件吗?但是我想要格式化的excel文件。即。:导出后在Excel文件上放置图像,字体大小、颜色、填充颜色等。所有的格式都需要从后面的代码中进行。

1 个解决方案

#1


1  

Your best shot is OpenXML SDK - http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx. It allows you to generate Excel files.

你的最佳选择是OpenXML SDK - http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx。它允许您生成Excel文件。

#1


1  

Your best shot is OpenXML SDK - http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx. It allows you to generate Excel files.

你的最佳选择是OpenXML SDK - http://msdn.microsoft.com/en-us/library/office/hh180830(v=office.14).aspx。它允许您生成Excel文件。