2009-07-24 5 views
1
내가 엑셀에서 데이터를 읽어 excel.So에서 일부 날짜 열이 있고에 바인딩 엑셀 시트에서 데이터를 읽고 데이터 gridview.There에 표시하고

날짜는 "02/02/2009 12:00:00 AM"형식으로 표시되지만 엑셀 열의 실제 데이터는 "2/2/2009"형식입니다. 날짜 형식을 변경하는 방법 datagridview에서. "{T 0}",의 GridView

되어 내가 데이터 세트에서 데이터를 결합하고 있기 때문에

내가 어떤 템플릿 열 또는 내가 대해 HTMLEncode = "거짓"DataFormatString = 설정 위치를 몰라 이렇게 설정 바운드 열을 해달라고 이럴 수있는 방법이 있어요. 제발 도와주세요.

다음 코드 샘플을 찾으십시오.

string OleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+ FileUpload1.PostedFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\""; 

string strSheetName = "Sheet1"; 
OleDbConnection oledbConnection; 
OleDbCommand oledbCommand; 
OleDbDataAdapter oledbAdapter; 

oledbCommand = new OleDbCommand(); 
oledbAdapter = new OleDbDataAdapter(); 
DataSet dsExcellData = new DataSet(); 

oledbConnection = new OleDbConnection(OleDbConnection); 
oledbConnection.Open(); 
oledbCommand.Connection = oledbConnection; 


oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; // i want to find this sheet name 
oledbAdapter.SelectCommand = oledbCommand; 
oledbAdapter.Fill(dsExcellData); 

oledbConnection.Close(); 

GridView1.DataSource = dsExcellData.Tables[0]; 

GridView1.DataBind(); 

=========================================== =============== 시도해 보았습니다.

dsExcellData.Tables [0]. 행 [행 개수] [ "날짜 _ 열"]. ToString()] = dsExcellData.Tables [0 ] .Rows [rowcount] [ "date_column"]. ToString()]. ​​ToString ("d");

값은 "mm/dd/yyyy"로 할당되지 않습니다. 다시 기본 시간 (mm/dd/yyyy hh : mm : ss AM)을 사용합니다.

============================================== ===============

데이터 세트를 gridview에 할당하는 중입니다. 데이터 세트가 mm/dd/yyyy 형식의 날짜 열을 읽는 것입니다. hh : mm : ss AM입니다. 데이터 세트의 데이터도 변경할 수 없습니다.

==============================================

우리는 DataGridView에의하여 ItemDataBound에 아래의 코드를 추가해야합니다 :

protected void dgValidatedData_ItemDataBound1(object sender, DataGridItemEventArgs e) 
{ 

     for (int i = 0; i <= e.Item.Cells.Count - 1; i++) 
     { 
      System.DateTime cellDate = default(System.DateTime); 
      if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate)) 
      { 
       e.Item.Cells[i].Text = string.Format("{0:d}", cellDate); 
      } 
     } 

} 
=============== 마침내

내가 ScottE에서 대답을 얻었다

+0

미리 모든 열 이름을 알고 계시나요, 아니면 동적입니까? – ScottE

+0

DB에서 가져올 열 이름을 알 수 있습니다. – Jebli

답변

2

"Ok"는 서식을 지정해야하는 날짜 인 열 이름 (여러 개일 수 있음)입니다. 이것은 물론 vb.net이지만, 당신은 그것을 분류 할 수 있습니다. 더 좋은 방법이있을 것이라고 확신합니다. 그러나 이것은 효과적입니다.당신이 날짜가 무슨 열을 모르는 경우

Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) 
    If e.Row.RowType = DataControlRowType.DataRow Then 
     For i As Integer = 0 To e.Row.Cells.Count - 1 
      If gv.HeaderRow.Cells(i).Text = "Item" Then 
       e.Row.Cells(i).Text = String.Format("{0:d}", CType(e.Row.Cells(i).Text, Date)) 
      End If 
     Next 
    End If 
End Sub 

또는, 다음은 잘 작동합니다 :

: 여기
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) 
    If e.Row.RowType = DataControlRowType.DataRow Then 
     For i As Integer = 0 To e.Row.Cells.Count - 1 
      Dim cellDate As Date 
      If Date.TryParse(e.Row.Cells(i).Text, cellDate) Then 
       e.Row.Cells(i).Text = String.Format("{0:d}", cellDate) 
      End If 
     Next 
    End If 
End Sub 
+0

안녕 당신은 코드 .I이있는 gridview를 사용하여 C#에서 코드를 찾아주십시오하고 작동하고 이걸 어째 있습니다 보호 무효 dgValidatedData_ItemDataBound1 (개체를 보낸 사람, DataGridItemEventArgs 전자)에 대한 { 을 (INT I = 0; 나는 <= e.Item.Cells.Count - 1; i ++) { cell.Date = default (System.DateTime); if (System.DateTime.TryParse (e.Item.Cells [i] .Text, out cellDate)) { e.Item.Cells [i] .Text = string.Format ("{0 : d}", cellDate); } } } } 감사합니다. – Jebli

+1

문제 없습니다. 그것이 당신을 위해 작동하는 경우에, 그것을 맞은 표를하십시오 - 이미 여기에서 너무 많은 의문없는 질문이있다! – ScottE

0

GridView 열에 정의해야하는 날짜 형식입니다. 예 :


<asp:GridView> 
... 
<asp:TemplateField> 
<ItemTemplate> 
    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Date", "{0:T}") %>'></asp:Label> 
    </ItemTemplate> 
... 
</asp:GridView> 
+0

항목 템플릿을 사용하고 있지 않습니다. 왜냐하면 나는 데이터를 동적으로 바인딩하고 있기 때문입니다. 나는 데이터베이스에서 검색 할 컬럼 이름의 컬럼 이름을 알고있을 것입니다. 게시물에 감사합니다. – Jebli

2

asp : BoundField로 바인딩하는 경우 htmlencode를 false로 설정해야합니다.

<asp:BoundField HtmlEncode="false" DataField="Blah" DataFormatString="{0:d}" /> 
+0

나는 ASP 바인딩 된 필드를 사용하고 있지 않습니다. 나는 데이터 집합에서 데이터 그리드에 데이터를 바인딩하고 있습니다. 귀하의 회신에 감사드립니다. – Jebli

0

가의 GridView에서 파생되는 사용자 지정 컨트롤을 사용하여 솔루션 우리가 항목에서 아래의 코드를 추가 할 필요가

:

using System; 
using System.Collections; 
using System.Web.UI.WebControls; 

namespace CustomControls { 

    public class FormattedGridView : GridView { 

    protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource) { 

     // Call base method and return the collection as an ArrayList 
     var columns = (ArrayList) base.CreateColumns(dataSource, useDataSource); 

     for (var i = 0; i < columns.Count; i++) { 

     var agf = columns[i] as AutoGeneratedField; 

     if (agf != null && agf.DataType == typeof(DateTime)) { 

      // create a new column because the AutoGeneratedField does not support 
      // the modification of the DataFormatString property 
      var bf = new BoundField(); 

      // copy some of the original properties 
      bf.DataField = agf.DataField; 
      bf.HeaderText = agf.HeaderText; 
      bf.HtmlEncode = false; 

      // set the format for the DateTime types 
      bf.DataFormatString = "{0:T}"; 

      // replace the existing auto-generated colums 
      columns[i] = bf; 
     } 

     } 

     return columns; 
    } 
    } 

} 
+0

안녕하세요, C# 3.5를 사용하지 않아서 죄송합니다. C# 2.0을 사용하고 있습니다. – Jebli

0

는 마침내 내가 ScottE에서 대답을 얻었다 DataGridView에의 바인딩 :

보호 공극 dg_ItemDataBound1 (객체 송신자 DataGridItemEventArgs E) {

for (int i = 0; i <= e.Item.Cells.Count - 1; i++) 
    { 
     System.DateTime cellDate = default(System.DateTime); 
     if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate)) 
     { 
      e.Item.Cells[i].Text = string.Format("{0:d}", cellDate); 
     } 
    } 

}

그러나 상기 코드 datagrig.It에 결합 된 모든 데이터를 검사 할 것이다 셀에서 datetime으로 데이터를 구문 분석하려고 시도합니다. 유효한 datetime 일 경우 데이터를 적용한 형식으로 변환합니다.