PDA

View Full Version : اکسپورت دیتا در word



minanazari
سه شنبه 13 مرداد 1394, 10:44 صبح
سلام و خسته نباشید

من توسط c# برنامه ای نوشتم که از اکسس اطلاعات را می خونه و چند تا رکورد تصادفی را بر می گردونه حالا من می خوام نتیجه را در فایل word به من خروجی بده و لازم به ذکر است که از datagridview استفاده نکردم بلکه از dataset استفاده کردم.

ممنون می شم راهنماییم کنید .

دلتنگ اسمان
سه شنبه 13 مرداد 1394, 14:57 عصر
با سلام
این کل کدها:
فقط یه نکته توی قسمت Reference--->.Net--<Microsoft.Office.Interop.Word version 12 رو اضافه کن.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;

namespace datasetToWord
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

string ConnectionString = @"server=localhost\SQLEXPRESS; database=test ;integrated security=true";

private void ExportdatasetToWord_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;

object Visible = true;

object start1 = 0;

object end1 = 0;


ApplicationClass WordApp = new ApplicationClass();

Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);

Range rng = adoc.Range(ref start1, ref missing);

DataTable data = selectData();

try
{
//DataSet data = new DataSet();

rng.Font.Name = "Georgia";
foreach (DataRow row in data.Rows)
{
rng.InsertAfter(row[0].ToString());

}

object filename = @"D:\MyWord.doc";

adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,

ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

WordApp.Visible = true;

}

catch (Exception ex)
{

MessageBox.Show(ex.Message);

}
}

public DataTable selectData()
{
SqlConnection con = new SqlConnection();
SqlCommand com = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt = new DataTable();
con.ConnectionString = ConnectionString;
com.Connection = con;
con.Open();

SqlDataAdapter da = new SqlDataAdapter("SELECT name, family FROM tb1", con.ConnectionString);
DataTable dt1 = new DataTable();
da.Fill(dt1);

con.Close();
com.Dispose();
con.Dispose();
return dt1;
}
}
}