201406
發生錯誤訊息:具有潛在危險 Request.Form 的值已從用戶端...偵測到
當<pages validateRequest=ture...>(預設true)此時只要textbox有輸入html,送出資料後就會顯示具有潛在危險 Request.Form 的值已從用戶端偵測到;如果要關閉請先找到pages標籤並加上 validateRequest="false"或者在每個網頁的開頭<%@ Page ... %>加上ValidateRequest="false",此時送出後如果還是顯示一樣的錯誤訊息,請在system.web標籤之間加上<httpRuntime requestValidationMode="2.0"/> (此標籤只有.net 4才有)
2014年6月25日 星期三
2014年6月20日 星期五
JQuery UI accordion 設定標題、內容位置、cookie紀錄目前點擊的項目
參考1:asp.net+jquery accordion 按鈕點擊會收縮
說明:參考1的資料符合我要實作的需求,在此作了些補充及修改。另外下方的程式碼,少了另外一個登入的頁面,當使用者登入成功後,將會指定 $.cookie('index',0); ,轉到另外一個頁面(下方的程式碼)後accordion就會預設展開我們要展開的項目,因為有指定cookie的關係,當使用者重新整理時,accordion就會停留在目前點擊的項目。
程式碼如下
<head>
<title></title>
<link rel="stylesheet" href="themes/base/jquery.ui.all.css">
<script type="text/javascript" src="Scripts/jquery.js"></script>
<script src="Scripts/jquery.cookie.js"></script>
<script src="Scripts/jquery.ui.core.js"></script>
<script src="Scripts/jquery.ui.widget.js"></script>
<script src="Scripts/jquery.ui.accordion.js"></script>
<script>
$(function () {
//同時設定 active: false,collapsible: true 可讓項目呈現不摺疊(不展開)狀態
$('#accordion').accordion({
activate: function (event, ui) {
//當click時觸發此處
if (($.cookie('index') == null) || ($.cookie('index')==undefined)) {
$.cookie('index', 0);
}else{
$.cookie('index', $('#accordion').accordion('option', 'active'));
};
},
active: parseInt($.cookie('saved_index'),10),
collapsible: true,
});
});
</script>
<style>
/**設定摺疊標題文字大小 padding: .5em .5em .5em .7em;*/
.ui-accordion .ui-accordion-header { display: block; font-size: 16px; }
/*設定摺疊標題為置**/
.ui-accordion .ui-accordion-icons {padding-left: 1.5em;}
/**.ui-accordion .ui-accordion-content 設定摺疊內容文字位置*/
.ui-accordion .ui-accordion-content {padding: 0.5em 0.5em; border-top: 0; overflow: auto; zoom: 1;}
</style>
<link type="text/css" rel="stylesheet" href="public_css.css"/>
</head>
<body>
<form id="form1">
<div id="accordion">
<h4>項目1</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目2</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目3</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
</div>
</form>
</body>
</html>
說明:參考1的資料符合我要實作的需求,在此作了些補充及修改。另外下方的程式碼,少了另外一個登入的頁面,當使用者登入成功後,將會指定 $.cookie('index',0); ,轉到另外一個頁面(下方的程式碼)後accordion就會預設展開我們要展開的項目,因為有指定cookie的關係,當使用者重新整理時,accordion就會停留在目前點擊的項目。
程式碼如下
<head>
<title></title>
<link rel="stylesheet" href="themes/base/jquery.ui.all.css">
<script type="text/javascript" src="Scripts/jquery.js"></script>
<script src="Scripts/jquery.cookie.js"></script>
<script src="Scripts/jquery.ui.core.js"></script>
<script src="Scripts/jquery.ui.widget.js"></script>
<script src="Scripts/jquery.ui.accordion.js"></script>
<script>
$(function () {
//同時設定 active: false,collapsible: true 可讓項目呈現不摺疊(不展開)狀態
$('#accordion').accordion({
activate: function (event, ui) {
//當click時觸發此處
if (($.cookie('index') == null) || ($.cookie('index')==undefined)) {
$.cookie('index', 0);
}else{
$.cookie('index', $('#accordion').accordion('option', 'active'));
};
},
active: parseInt($.cookie('saved_index'),10),
collapsible: true,
});
});
</script>
<style>
/**設定摺疊標題文字大小 padding: .5em .5em .5em .7em;*/
.ui-accordion .ui-accordion-header { display: block; font-size: 16px; }
/*設定摺疊標題為置**/
.ui-accordion .ui-accordion-icons {padding-left: 1.5em;}
/**.ui-accordion .ui-accordion-content 設定摺疊內容文字位置*/
.ui-accordion .ui-accordion-content {padding: 0.5em 0.5em; border-top: 0; overflow: auto; zoom: 1;}
</style>
<link type="text/css" rel="stylesheet" href="public_css.css"/>
</head>
<body>
<form id="form1">
<div id="accordion">
<h4>項目1</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目2</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
<h4>項目3</h4>
<div>
<a>子項目1</a><br/>
<a>子項目2</a>
</div>
</div>
</form>
</body>
</html>
2014年6月10日 星期二
ASP.NET 使用DataSet+LINQ JOIN(關聯)資料表 (VB.NET語法)
參考資料1:聯結運算子 (LINQ to DataSet)
參考資料2:使用 Joins 以 LINQ 合併資料 (Visual Basic)
說明:本篇主要是參考「參考資料1」,來進行實作。
前置作業:
1.請準備好兩個資料表,分別為 學生(Student)、班級(Class);
學生資料表欄位只需要三個欄位,分別為班級編號(class_id)、學號(stud_id)、姓名(stud_name)。
班級資料表欄位只需要兩個欄位,分別為班級編號(class_id)、班級名稱(class_name)。
2.請在Html中放入一個GridView,之後抓出來的資料丟到GridView
Code如下
Imports System
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.Common
Imports System.Globalization
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim ds As DataSet = New DataSet
ds.Locale = CultureInfo.InvariantCulture
Dim connectionString As String = Nothing
connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection(connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select st.class_id,st.stud_id,st.stud_name from Student as st where st.stud_id like '111%'", connection)
connection.Open()
adapter.Fill(ds, "student")
End Using
Using connection As SqlConnection = New SqlConnection(connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select cl.class_id,cl.class_name from class as cl", connection)
connection.Open()
adapter.Fill(ds, "class")
End Using
Dim stud_dt As DataTable = ds.Tables("student")
Dim class_dt As DataTable = ds.Tables("class")
Dim query = _
From st In stud_dt.AsEnumerable() _
Join cl In class_dt.AsEnumerable() _
On st.Field(Of String)("class_id") Equals _
cl.Field(Of String)("class_id") _
Select New With _
{ _
.class_id = st.Field(Of String)("class_id"), _
.class_name = cl.Field(Of String)("class_name"), _
.stud_id = st.Field(Of String)("stud_id"), _
.stud_name = st.Field(Of String)("stud_name") _
}
'可印出資料
'For Each strdata In query
' Response.Write(strdata.class_id & vbTab & _
' strdata.class_name & vbTab & _
' strdata.stud_id & vbTab & _
' strdata.stud_name)
'Next
GridView1.DataSource = query
GridView1.DataBind()
End If
End Sub
2014年6月9日 星期一
ASP.NET 兩個DataSet合併到另一個DataSet,並JOIN(關聯)DataSet中的資料(VB.NET語法)
參考資料1:瀏覽 DataRelation (ADO.NET)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim connectionString As String = Nothing
Dim n1 As DataSet = Nothing
n1 = New DataSet("newtable")
Dim stud As DataSet = Nothing, cl As DataSet = Nothing
connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select st.班級編號,st.學號,st.姓名 from 學生 as st where st.學號 like '111%'", connection)
connection.Open()
stud = New DataSet()
adapter.Fill(stud, "student")
End Using
n1.Merge(stud.Tables(0))
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select cl.班級編號,cl.班級名稱 from 班級 as cl", connection)
connection.Open()
cl = New DataSet()
adapter.Fill(cl, "class")
End Using
n1.Merge(cl.Tables(0))
'第四個參數 預設為True代表使用條件約束
Dim StudClassRelation As DataRelation = n1.Relations.Add("StudClass", n1.Tables("student").Columns("班級編號"), n1.Tables("class").Columns("班級編號"), False)
Dim studRow, classRow As DataRow
For Each studRow In n1.Tables("student").Rows
Response.Write("st.班級編號:" & studRow("班級編號").ToString() & " st.學號:" & studRow("學號").ToString())
For Each classRow In studRow.GetChildRows(StudClassRelation)
Response.Write(" cl.班級編號:" & classRow("班級編號").ToString() & " cl.班級名稱:" & classRow("班級名稱").ToString() & "<br/>")
Next
Next
End If
End Sub
ASP.NET 兩個DataSet合併到另一個DataSet,並Select DataSet中的某一筆資料(VB.NET語法)
說明:先下SQL指令,分別Select兩個不同的資料庫-資料表,並將資料合併在同一個DataSet,且針對DataSet Select某一筆資料。
參考資料1:DataSet.Merge 方法 (DataTable)
參考資料2:DataTable.Select Method (String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim connectionString As String = Nothing
Dim n1 As DataSet = Nothing '將資料合併在這個DataSet
n1 = New DataSet("newtable")
Dim student1 As DataSet = Nothing, student2 As DataSet = Nothing
connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select 班級,學號,姓名 from Student where 學號 like '400%'", connection)
connection.Open()
student1 = New DataSet()
adapter.Fill(student1, "student1")
End Using
n1.Merge(student1.Tables(0))
connectionString = "Server=127.0.0.1;Database=test2;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select 班級,學號,姓名 from Student where 學號 like '899%'", connection)
connection.Open()
student2 = New DataSet()
adapter.Fill(student2, "student1") '這裡的student1如果更改成student2,合併後n1.Tables(0)只能看到student1的資料,而n1.Tables(1)才會看到student2的資料
End Using
n1.Merge(student2.Tables(0))
GridView1.DataSource = n1.Tables(0)
GridView1.DataBind()
Dim expression As String
expression = "stud_no = '89906141'" '要搜尋的條件
Dim foundRows() As DataRow = Nothing
foundRows = n1.Tables(0).Select(expression) '使用Select搜尋資料
Dim i As Integer
For i = 0 To foundRows.GetUpperBound(0)
For j = 0 To foundRows(i).ItemArray.Count - 1
If j = foundRows(i).ItemArray.Count - 1 Then
Label1.Text = Label1.Text & foundRows(i)(j)
Else
Label1.Text = Label1.Text & foundRows(i)(j) & ","
End If
Next
Next
End If
End Sub
參考資料1:DataSet.Merge 方法 (DataTable)
參考資料2:DataTable.Select Method (String)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim connectionString As String = Nothing
Dim n1 As DataSet = Nothing '將資料合併在這個DataSet
n1 = New DataSet("newtable")
Dim student1 As DataSet = Nothing, student2 As DataSet = Nothing
connectionString = "Server=127.0.0.1;Database=test1;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select 班級,學號,姓名 from Student where 學號 like '400%'", connection)
connection.Open()
student1 = New DataSet()
adapter.Fill(student1, "student1")
End Using
n1.Merge(student1.Tables(0))
connectionString = "Server=127.0.0.1;Database=test2;uid=test;pwd=test"
Using connection As SqlConnection = New SqlConnection( _
connectionString)
Dim adapter As SqlDataAdapter = New SqlDataAdapter( _
"select 班級,學號,姓名 from Student where 學號 like '899%'", connection)
connection.Open()
student2 = New DataSet()
adapter.Fill(student2, "student1") '這裡的student1如果更改成student2,合併後n1.Tables(0)只能看到student1的資料,而n1.Tables(1)才會看到student2的資料
End Using
n1.Merge(student2.Tables(0))
GridView1.DataSource = n1.Tables(0)
GridView1.DataBind()
Dim expression As String
expression = "stud_no = '89906141'" '要搜尋的條件
Dim foundRows() As DataRow = Nothing
foundRows = n1.Tables(0).Select(expression) '使用Select搜尋資料
Dim i As Integer
For i = 0 To foundRows.GetUpperBound(0)
For j = 0 To foundRows(i).ItemArray.Count - 1
If j = foundRows(i).ItemArray.Count - 1 Then
Label1.Text = Label1.Text & foundRows(i)(j)
Else
Label1.Text = Label1.Text & foundRows(i)(j) & ","
End If
Next
Next
End If
End Sub
2014年6月6日 星期五
JQuery 應用篇
201706
1.取得table中的td欄位資料。
//jquery-1.11.3.js
$('#table1 > tbody > tr').each(function () {
//nth-child(3)取得第4個欄位資料
//$(this).find('td:nth-child(3)').text().trim()
//如果要取得欄位中的TextBox就使用eq,取得第5個欄位的input
//$(this).find('td:eq(4) input[type="text"]').val();
});
2.取得table中第一列之後的所有資料。
通常第一列會是表頭,如果要取得第一列之後的資料列,請使用下方的程式碼。
//:not排除、:first表格的第一列
//:not(:first)除了表格的第一行,其他的資料列都要
$('#table1 > tbody > tr:not(:first)').each(function () {
...
});
201705
1.檢查元素存不存在可以使用length來判斷,等於0不存在、>0代表存在。
if ($('#span_mess').length > 0) {
//存在
}else{
//不存在
};
201512
1.設定某個容器底下的checkbox全部勾選、全部取消(此例以table底下的checkbox為例)
//使用 jquery 版本v1.8.2
function CB1_checked(str_pid, int_dis) {
if (int_dis==1) {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', true); //全部勾選
} else {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', false); //全部取消
};
};
201411
1. 移除屬性(removeAttr)
$('#button1').removeAttr('onclick'); //移除button1 onclick
2. readonly
$('#id1').attr('readonly',true);
201406
1. HTML radio
1-1. 取得 radio 是否有選取項目
var str_iden=$('input[type="radio"][name="iden"]:checked').val();
if (str_iden==undefined){
alert('您的身份尚未填寫');
return false; //在script標籤中,回傳false 會有終止程式執行的效果
};
1-2. radio 單選某個項目
$('input[type="radio"][name="iden"][value="1"]').attr("checked",true);
1-3. radio 停用與啟用
$('#input[type="radio"][name="iden"]').attr('disabled',true); //停用
1-4. 取得class是sall的元素,底下input type是radio,其值是1的項目(個人覺得如果是使用asp.net建議使用prop)。
$('[class="sall"] input[type="radio"][value="1"]').prop("checked", true);
2. HTML Checkbox
2-1. checkbox 是否有勾選此項目(適用於單一一個checkbox)
法1.
if ($('input[type="checkbox"][name="tt"]').attr('checked')){
alert('您已勾選此項目');
}else{
alert('您已取消此項目');
};
法2.(適用於JQuery 1.6以後的版本)
將 $('input[type="checkbox"][name="tt"]').attr('checked') 改成
$('input[type="checkbox"][name="tt"]').prop('checked')
2-2. 設定CheckBox勾選
$('input[type="checkbox"][name="tt"]').attr('checked',true); //可用在低版本的JQuery
補充:使用 attr('checked', true) 與 prop("checked", true)差別在於attr('checked', true)會在標籤裡增加checked的屬性,而 prop("checked", true)則不會在標籤裡增加checked屬性。
3. HTML Select
2-1. 取得下拉式選單選取的值及項目
$('select[name="s1"] option:selected').val(); //value
$('select[id="DDL1"] option:selected').text(); //項目
2-2. 設定下拉式選單項目為選取狀態(適用於JQuery低版本)
$('select[name="Area"] option[value="100"]').attr("selected",true);
2018/03/26 如果我的Html Select有設定class,例如我的class="hello",我也可以這樣子去設定Select要停留在哪一個選項。(使用的jquery版本是jquery-1.11.3)
$('.hello').val('0');
1.取得table中的td欄位資料。
//jquery-1.11.3.js
$('#table1 > tbody > tr').each(function () {
//nth-child(3)取得第4個欄位資料
//$(this).find('td:nth-child(3)').text().trim()
//如果要取得欄位中的TextBox就使用eq,取得第5個欄位的input
//$(this).find('td:eq(4) input[type="text"]').val();
});
2.取得table中第一列之後的所有資料。
通常第一列會是表頭,如果要取得第一列之後的資料列,請使用下方的程式碼。
//:not排除、:first表格的第一列
//:not(:first)除了表格的第一行,其他的資料列都要
$('#table1 > tbody > tr:not(:first)').each(function () {
...
});
201705
1.檢查元素存不存在可以使用length來判斷,等於0不存在、>0代表存在。
if ($('#span_mess').length > 0) {
//存在
}else{
//不存在
};
201512
1.設定某個容器底下的checkbox全部勾選、全部取消(此例以table底下的checkbox為例)
//使用 jquery 版本v1.8.2
function CB1_checked(str_pid, int_dis) {
if (int_dis==1) {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', true); //全部勾選
} else {
$('#' + str_pid + ' :input[type="checkbox"]').attr('checked', false); //全部取消
};
};
201411
1. 移除屬性(removeAttr)
$('#button1').removeAttr('onclick'); //移除button1 onclick
2. readonly
$('#id1').attr('readonly',true);
201406
1. HTML radio
1-1. 取得 radio 是否有選取項目
var str_iden=$('input[type="radio"][name="iden"]:checked').val();
if (str_iden==undefined){
alert('您的身份尚未填寫');
return false; //在script標籤中,回傳false 會有終止程式執行的效果
};
1-2. radio 單選某個項目
$('input[type="radio"][name="iden"][value="1"]').attr("checked",true);
1-3. radio 停用與啟用
$('#input[type="radio"][name="iden"]').attr('disabled',true); //停用
1-4. 取得class是sall的元素,底下input type是radio,其值是1的項目(個人覺得如果是使用asp.net建議使用prop)。
$('[class="sall"] input[type="radio"][value="1"]').prop("checked", true);
2. HTML Checkbox
2-1. checkbox 是否有勾選此項目(適用於單一一個checkbox)
法1.
if ($('input[type="checkbox"][name="tt"]').attr('checked')){
alert('您已勾選此項目');
}else{
alert('您已取消此項目');
};
法2.(適用於JQuery 1.6以後的版本)
將 $('input[type="checkbox"][name="tt"]').attr('checked') 改成
$('input[type="checkbox"][name="tt"]').prop('checked')
2-2. 設定CheckBox勾選
$('input[type="checkbox"][name="tt"]').attr('checked',true); //可用在低版本的JQuery
補充:使用 attr('checked', true) 與 prop("checked", true)差別在於attr('checked', true)會在標籤裡增加checked的屬性,而 prop("checked", true)則不會在標籤裡增加checked屬性。
3. HTML Select
2-1. 取得下拉式選單選取的值及項目
$('select[name="s1"] option:selected').val(); //value
$('select[id="DDL1"] option:selected').text(); //項目
2-2. 設定下拉式選單項目為選取狀態(適用於JQuery低版本)
$('select[name="Area"] option[value="100"]').attr("selected",true);
2018/03/26 如果我的Html Select有設定class,例如我的class="hello",我也可以這樣子去設定Select要停留在哪一個選項。(使用的jquery版本是jquery-1.11.3)
$('.hello').val('0');
2014年4月2日 星期三
ASP.NET 使用Open Xml SDK 輸出Word檔
參考1:[Office]使用 OpenXML SDK 建立 Word 文件檔
參考2:[Office開發系列] 使用 OpenXML 將資料庫中的資料整合到 Word 文件中,且不假手 Office 物件模型
參考3:【雛型】Docx套版列印功能試作
參考4:How to: Insert a picture into a word processing document (Open XML SDK)
前置作業:
1.必須先下載安裝 Open XML SDK (我是使用 Open XML SDK 2.5 for Microsoft Office )
此篇純粹記錄程式碼
功能說明:取得現有的word檔,並在Word檔中的Table插入資料及圖片。
現有的Word檔(檔案名稱 testDoc.docx),格式如下圖:
程式產生出的Word檔,如下圖:
Code:
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports A = DocumentFormat.OpenXml.Drawing
Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing
Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures
'===============================================
Imports System.IO
Partial Class test_word
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str_path As String = "C:\Users\SchoolDev\Desktop\test.docx"
Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(str_path, WordprocessingDocumentType.Document)
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
mainPart.Document = New Document()
Dim body As Body = mainPart.Document.AppendChild(New Body())
Dim par As Paragraph = body.AppendChild(New Paragraph())
Dim run As Run = par.AppendChild(New Run())
run.AppendChild(New Text("Hello,ASP.NET利用Open Xml Sdk產生Word檔"))
End Using
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fs As FileStream = ReadTemplateFile()
Dim doc As WordprocessingDocument = WordprocessingDocument.Open(fs, True)
Dim document As Document = doc.MainDocumentPart.Document
Dim table As Table = document.Body.GetFirstChild(Of Table)()
Dim lastRow As TableRow = table.GetFirstChild(Of TableRow)()
For y1 As Integer = 0 To 3
Dim newRow As TableRow = CreateItemRow(y1, 3, doc)
table.InsertAfter(newRow, lastRow)
lastRow = newRow
Next
doc.MainDocumentPart.Document.Save()
doc.Close()
fs.Close()
End Sub
Function ReadTemplateFile() As FileStream
Dim newFileName As String = "C:\Users\SchoolDev\Desktop\" & "doc_" & DateTime.Now.ToString("yyyyMMddHHmmss") & ".docx"
File.Copy(Server.MapPath("testDoc.docx"), newFileName)
Return New FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
End Function
Function CreateItemRow(ByVal row_y As Integer, ByVal cell_x As Integer, ByVal word1 As WordprocessingDocument) As TableRow
Dim tableRow1 As TableRow = New TableRow()
For x1 As Integer = 0 To cell_x - 1
Dim tableCell1 As TableCell = New TableCell()
Dim par1 As Paragraph = New Paragraph()
Dim run1 As Run = New Run()
Dim text1 As Text = New Text()
text1.Text = "name" & row_y & "-" & x1
run1.Append(text1)
Dim img1 As ImagePart = word1.MainDocumentPart.AddImagePart(ImagePartType.Png)
Using imgstream As New FileStream(Server.MapPath("./images/Symbol.png"), FileMode.Open)
img1.FeedData(imgstream)
End Using
'DW.Extent(){.Cx = 192000L, .Cy = 192000L} Cx調整寬度 Cy調整高度
Dim relationshipId As String = word1.MainDocumentPart.GetIdOfPart(img1)
Dim element = New Drawing( _
New DW.Inline( _
New DW.Extent() With {.Cx = 192000L, .Cy = 192000L}, _
New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
New DW.NonVisualGraphicFrameDrawingProperties( _
New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
), _
New A.Graphic(New A.GraphicData( _
New PIC.Picture( _
New PIC.NonVisualPictureProperties( _
New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Picture.png"}, _
New PIC.NonVisualPictureDrawingProperties() _
), _
New PIC.BlipFill( _
New A.Blip( _
New A.BlipExtensionList( _
New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
New A.Stretch( _
New A.FillRectangle() _
) _
), _
New PIC.ShapeProperties( _
New A.Transform2D( _
New A.Offset() With {.X = 0L, .Y = 0L}, _
New A.Extents() With {.Cx = 792000L, .Cy = 792000L}), _
New A.PresetGeometry( _
New A.AdjustValueList() _
) With {.Preset = A.ShapeTypeValues.Rectangle} _
) _
) _
) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
) _
) With {.DistanceFromTop = 0UI, _
.DistanceFromBottom = 0UI, _
.DistanceFromLeft = 0UI, _
.DistanceFromRight = 0UI} _
)
run1.Append(element)
par1.Append(run1)
tableCell1.Append(par1)
tableRow1.Append(tableCell1)
Next
Return tableRow1
End Function
End Class
參考2:[Office開發系列] 使用 OpenXML 將資料庫中的資料整合到 Word 文件中,且不假手 Office 物件模型
參考3:【雛型】Docx套版列印功能試作
參考4:How to: Insert a picture into a word processing document (Open XML SDK)
前置作業:
1.必須先下載安裝 Open XML SDK (我是使用 Open XML SDK 2.5 for Microsoft Office )
此篇純粹記錄程式碼
功能說明:取得現有的word檔,並在Word檔中的Table插入資料及圖片。
現有的Word檔(檔案名稱 testDoc.docx),格式如下圖:
程式產生出的Word檔,如下圖:
Code:
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports A = DocumentFormat.OpenXml.Drawing
Imports DW = DocumentFormat.OpenXml.Drawing.Wordprocessing
Imports PIC = DocumentFormat.OpenXml.Drawing.Pictures
'===============================================
Imports System.IO
Partial Class test_word
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim str_path As String = "C:\Users\SchoolDev\Desktop\test.docx"
Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(str_path, WordprocessingDocumentType.Document)
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
mainPart.Document = New Document()
Dim body As Body = mainPart.Document.AppendChild(New Body())
Dim par As Paragraph = body.AppendChild(New Paragraph())
Dim run As Run = par.AppendChild(New Run())
run.AppendChild(New Text("Hello,ASP.NET利用Open Xml Sdk產生Word檔"))
End Using
End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim fs As FileStream = ReadTemplateFile()
Dim doc As WordprocessingDocument = WordprocessingDocument.Open(fs, True)
Dim document As Document = doc.MainDocumentPart.Document
Dim table As Table = document.Body.GetFirstChild(Of Table)()
Dim lastRow As TableRow = table.GetFirstChild(Of TableRow)()
For y1 As Integer = 0 To 3
Dim newRow As TableRow = CreateItemRow(y1, 3, doc)
table.InsertAfter(newRow, lastRow)
lastRow = newRow
Next
doc.MainDocumentPart.Document.Save()
doc.Close()
fs.Close()
End Sub
Function ReadTemplateFile() As FileStream
Dim newFileName As String = "C:\Users\SchoolDev\Desktop\" & "doc_" & DateTime.Now.ToString("yyyyMMddHHmmss") & ".docx"
File.Copy(Server.MapPath("testDoc.docx"), newFileName)
Return New FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
End Function
Function CreateItemRow(ByVal row_y As Integer, ByVal cell_x As Integer, ByVal word1 As WordprocessingDocument) As TableRow
Dim tableRow1 As TableRow = New TableRow()
For x1 As Integer = 0 To cell_x - 1
Dim tableCell1 As TableCell = New TableCell()
Dim par1 As Paragraph = New Paragraph()
Dim run1 As Run = New Run()
Dim text1 As Text = New Text()
text1.Text = "name" & row_y & "-" & x1
run1.Append(text1)
Dim img1 As ImagePart = word1.MainDocumentPart.AddImagePart(ImagePartType.Png)
Using imgstream As New FileStream(Server.MapPath("./images/Symbol.png"), FileMode.Open)
img1.FeedData(imgstream)
End Using
'DW.Extent(){.Cx = 192000L, .Cy = 192000L} Cx調整寬度 Cy調整高度
Dim relationshipId As String = word1.MainDocumentPart.GetIdOfPart(img1)
Dim element = New Drawing( _
New DW.Inline( _
New DW.Extent() With {.Cx = 192000L, .Cy = 192000L}, _
New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
New DW.NonVisualGraphicFrameDrawingProperties( _
New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
), _
New A.Graphic(New A.GraphicData( _
New PIC.Picture( _
New PIC.NonVisualPictureProperties( _
New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Picture.png"}, _
New PIC.NonVisualPictureDrawingProperties() _
), _
New PIC.BlipFill( _
New A.Blip( _
New A.BlipExtensionList( _
New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
New A.Stretch( _
New A.FillRectangle() _
) _
), _
New PIC.ShapeProperties( _
New A.Transform2D( _
New A.Offset() With {.X = 0L, .Y = 0L}, _
New A.Extents() With {.Cx = 792000L, .Cy = 792000L}), _
New A.PresetGeometry( _
New A.AdjustValueList() _
) With {.Preset = A.ShapeTypeValues.Rectangle} _
) _
) _
) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
) _
) With {.DistanceFromTop = 0UI, _
.DistanceFromBottom = 0UI, _
.DistanceFromLeft = 0UI, _
.DistanceFromRight = 0UI} _
)
run1.Append(element)
par1.Append(run1)
tableCell1.Append(par1)
tableRow1.Append(tableCell1)
Next
Return tableRow1
End Function
End Class
訂閱:
文章 (Atom)

