asp.netにExcelファイルをアップロードして表示するためのコーディングを行いましたが、問題は次のとおりです。
1)Excelファイルのシート名を知る方法(デフォルトシートとしてsheet1を使用していますが、ユーザーが異なるシート名を持つExcelファイルをアップロードしようとするとエラーが表示されます
2) Excel ファイルのヘッダーのような Excel ファイルのプロパティを知る方法、データの色とサイズ、フォントは? 私が表示している私の出力がExcelファイルと同じように見えるように
以下は私のコードです
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
namespace ExcelToAsp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnUpload_Click(object sender, EventArgs e)
{
if ((TxtFilePath.HasFile))
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string strFileType =
System.IO.Path.GetExtension(TxtFilePath.FileName).ToString().ToLower();
//Check file type
if (strFileType == ".xls" || strFileType == ".xlsx")
TxtFilePath.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
else
{
LblMsg.Text = "Only excel files allowed";
LblMsg.ForeColor = System.Drawing.Color.Red;
LblMsg.Visible = true;
return;
}
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
query = "SELECT * FROM [Sheet1$]";//query = "SELECT [Country],[Capital] FROM [Sheet1$] WHERE[Currency]=’Rupee’"//query = "SELECT [Country],[Capital] FROM [Sheet1$]"
//Create the connection object
conn = new OleDbConnection(connString);
//Open connection
if (conn.State == ConnectionState.Closed) conn.Open();
//Create the command object
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GrvExcelData.DataSource = ds.Tables[0];
GrvExcelData.DataBind();
LblMsg.Text = "Data retrieved successfully! Total Records:" + ds.Tables[0].Rows.Count;
LblMsg.ForeColor = System.Drawing.Color.Green;
LblMsg.Visible = true;
da.Dispose();
conn.Close();
conn.Dispose();
}
else
{
LblMsg.Text = "Please select an excel file first";
LblMsg.ForeColor = System.Drawing.Color.Red;
LblMsg.Visible = true;
}
}
}
}