使用C编写程序,将数据填充入Word表格并存入数据库 (c word表格 填充数据库)

随着计算机技术的不断进步,数据的处理和管理变得越来越重要。在许多工作中,我们需要将数据整理成表格的形式进行处理和统计,这就需要用到电子表格软件。而对于一些特定的工作,需要将表格中的数据存储到数据库中,以便于后续的数据分析和使用。本文将介绍如何。

一、使用C操作Word表格

要使用C操作Word表格,我们首先需要安装一个Word的开发包。这里推荐使用Microsoft Office Interop Word Library。安装完之后,我们就可以在C中利用COM(Component Object Model,组件对象模型)来操作Word。

具体来说,我们需要做以下几个操作:

1. 创建Word应用程序对象

使用下列代码即可创建一个Word应用程序对象:

“`c

#include

#include

// 创建Word应用程序对象

void create_word_app_obj() {

HRESULT hr;

// 初始化COM库

CoInitialize(NULL);

// 创建Word应用程序对象

IApplicationPtr iapp(“Word.Application”);

// 设置属性

iapp->PutVisible(TRUE);

// 得到Documents对象

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

// 新建一个Document

hr = idisp->CallMethod(L”Add”, &idoc);

}

“`

2. 创建表格

使用下列代码即可创建一个2行3列的Word表格:

“`c

// 创建表格

void create_table() {

HRESULT hr;

IApplicationPtr iapp(“Word.Application”);

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

hr = idisp->CallMethod(L”Add”, &idoc);

// 得到Selection对象

ISelectionPtr isel(iapp->GetSelection());

// 插入表格

isel->CallMethod(L”TablesAdd”, NULL, 2, 3);

}

“`

3. 填充表格数据

使用下列代码即可将数据填充入表格:

“`c

// 填充表格数据

void fill_data() {

HRESULT hr;

IApplicationPtr iapp(“Word.Application”);

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

hr = idisp->CallMethod(L”Add”, &idoc);

// 得到Selection对象

ISelectionPtr isel(iapp->GetSelection());

// 插入表格

isel->CallMethod(L”TablesAdd”, NULL, 2, 3);

// 填充表格数据

IDispatchPtr itab = isel->GetTables()->Item(1);

IDispatchPtr icells = itab->GetRange();

int data[2][3] = { {1, 2, 3}, {4, 5, 6} };

for (int i = 0; i

for (int j = 0; j

IDispatchPtr icell = icells->CallMethod(L”Item”, &vtMissing, i + 1, j + 1);

icell->PutRangeText(_bstr_t(data[i][j]), vtMissing);

}

}

}

“`

二、将数据存入数据库

将数据存储到数据库中可以使用ODBC (Open DataBase Connectivity)技术。ODBC是一种支持异构数据库间通信的API接口标准。使用的过程中,需要先安装ODBC数据库驱动程序。

具体来说,我们需要做以下几个操作:

1. 连接数据库

使用下列代码即可连接指定的数据库:

“`c

#include

#include

#include

RETCODE retcode;

SQLHANDLE henv;

SQLHANDLE hdbc;

SQLHANDLE hstmt;

SQLWCHAR* dsn = L”test”;

SQLWCHAR* uid = L”root”;

SQLWCHAR* pwd = L”123456″;

// 连接数据库

void connect() {

// 初始化环境句柄

retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

// 初始化数据库句柄

retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

// 连接数据库

retcode = SQLConnect(hdbc, dsn, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);

}

“`

2. 插入数据

使用下列代码即可将数据插入到指定的数据库表中:

“`c

// 插入数据

void insert_data() {

// 创建并执行SQL语句

SQLWCHAR* sql = L”INSERT INTO mytable (id, name, age) VALUES (?, ?, ?)”;

retcode = SQLPrepare(hstmt, sql, SQL_NTS);

int data[2][3] = { {1, 2, 3}, {4, 5, 6} };

for (int i = 0; i

SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_INTEGER, 0, 0, &data[i][0], 0, NULL);

SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_VARCHAR, 0, 0, “Amy”, 0, NULL);

SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_INTEGER, 0, 0, &data[i][1], 0, NULL);

retcode = SQLExecute(hstmt);

}

}

“`

三、程序实现

将以上内容整合起来,就可以得到一个完整的C程序,将数据填充入Word表格并存入数据库:

“`c

#include

#include

#include

#include

#include

// 创建Word应用程序对象

void create_word_app_obj() {

HRESULT hr;

// 初始化COM库

CoInitialize(NULL);

// 创建Word应用程序对象

IApplicationPtr iapp(“Word.Application”);

// 设置属性

iapp->PutVisible(TRUE);

// 得到Documents对象

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

// 新建一个Document

hr = idisp->CallMethod(L”Add”, &idoc);

}

// 创建表格

void create_table() {

HRESULT hr;

IApplicationPtr iapp(“Word.Application”);

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

hr = idisp->CallMethod(L”Add”, &idoc);

// 得到Selection对象

ISelectionPtr isel(iapp->GetSelection());

// 插入表格

isel->CallMethod(L”TablesAdd”, NULL, 2, 3);

}

// 填充表格数据

void fill_data() {

HRESULT hr;

IApplicationPtr iapp(“Word.Application”);

IDispatchPtr idisp = iapp->GetDocuments();

IDispatchPtr idoc;

hr = idisp->CallMethod(L”Add”, &idoc);

// 得到Selection对象

ISelectionPtr isel(iapp->GetSelection());

// 插入表格

isel->CallMethod(L”TablesAdd”, NULL, 2, 3);

// 填充表格数据

IDispatchPtr itab = isel->GetTables()->Item(1);

IDispatchPtr icells = itab->GetRange();

int data[2][3] = { {1, 2, 3}, {4, 5, 6} };

for (int i = 0; i

for (int j = 0; j

IDispatchPtr icell = icells->CallMethod(L”Item”, &vtMissing, i + 1, j + 1);

icell->PutRangeText(_bstr_t(data[i][j]), vtMissing);

}

}

}

// 连接数据库

void connect_database() {

RETCODE retcode;

SQLHANDLE henv;

SQLHANDLE hdbc;

SQLHANDLE hstmt;

SQLWCHAR* dsn = L”test”;

SQLWCHAR* uid = L”root”;

SQLWCHAR* pwd = L”123456″;

// 初始化环境句柄

retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);

retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

// 初始化数据库句柄

retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);

// 连接数据库

retcode = SQLConnect(hdbc, dsn, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);

}

// 插入数据

void insert_data() {

// 创建并执行SQL语句

SQLWCHAR* sql = L”INSERT INTO mytable (id, name, age) VALUES (?, ?, ?)”;

retcode = SQLPrepare(hstmt, sql, SQL_NTS);

int data[2][3] = { {1, 2, 3}, {4, 5, 6} };

for (int i = 0; i

SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_INTEGER, 0, 0, &data[i][0], 0, NULL);

SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_VARCHAR, 0, 0, “Amy”, 0, NULL);

SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_INTEGER, 0, 0, &data[i][1], 0, NULL);

retcode = SQLExecute(hstmt);

}

}

// 主函数

int mn() {

create_word_app_obj();

create_table();

fill_data();

connect_database();

insert_data();

return 0;

}

“`

四、

相关问题拓展阅读:

  • 如何向Word中写入数据,C#.net
  • web编程中怎样把word中的表格导入到数据库

如何向Word中写入数据,C#.net

您好。这个问题我以前曾经研究过,写一篇博文来讲述这个问题。

请参考我的博客,相信里面的内容应该是你要的。

《C#:简单实现动态数据生成Word文档并保存》

谢谢采纳。

利用如下代码即可:

C# code

public bool ExportWord(DataSet ds, string saveFileName)

{

bool fileSaved = false;

object filename = saveFileName;

try

{

Object Nothing = System.Reflection.Missing.Value;

//创建Word文档

Word.Application WordApp = new Word.ApplicationClass();

Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//文档中创建表格

WordApp.Selection.TypeParagraph();

Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 13, 5, ref Nothing, ref Nothing);

//设置表格样式

//newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;

//newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;

newTable.Columns.Width = 100f;

newTable.Columns.Width = 100f;

newTable.Columns.Width = 100f;

newTable.Columns.Width = 50f;

newTable.Columns.Width = 50f;

//填充表格内容

newTable.Cell(1, 1).Range.Text = “登记表”;

newTable.Cell(1, 1).Range.Bold = 3;//设置单元格中字体为粗体

//合并单元格

newTable.Cell(1, 1).Merge(newTable.Cell(1, 5));

WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

object missing = System.Reflection.Missing.Value;

object unit;

unit = Word.WdUnits.wdStory;

WordApp.Selection.EndKey(ref unit, ref missing);

WordApp.Selection.TypeParagraph();

//文件保存

WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

fileSaved = true;

WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

if (WordApp != null)

{

System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);

WordApp = null;

}

GC.Collect()

}

catch

{

fileSaved = false;

}

return fileSaved;

}

private void but_Table_Click(object sender, EventArgs e)

{

object Nothing = System.Reflection.Missing.Value;

object missing = System.Reflection.Missing.Value;

//创建Word文档

Word.Application wordApp = new Word.ApplicationClass();

Word.Document wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

wordApp.Visible = true;

//设置文档宽度

wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse(“2”));

wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11;

wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse(“2”));

Object start = Type.Missing;

Object end = Type.Missing;

PictureBox pp = new PictureBox(); //新建一个PictureBox控件

int p1 = 0;

for (int i = 0; i COM->Microsoft Word 11.0 Object Library

2、在.cs文件中添加CreateWordFile()方法

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

//添加二个命名控件

using Word;

using System.IO;

namespace WordFile

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

CreateWordFile(“D:\\dd.doc”);//调用方法

}

public string CreateWordFile(string CheckedInfo)

{

string message = “”;

try

{

Object Nothing = System.Reflection.Missing.Value;

Directory.CreateDirectory(“D:/CNSI”); //创建文件所在目录

string name = “CNSI_” + DateTime.Now.ToLongDateString() + “.doc”;//文件名

object filename = ” + name; //文件保存路径

//创建Word文档

Word.Application WordApp = new Word.ApplicationClass();

Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//添加页眉

WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;

WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;

WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(“”);

WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐

WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置

WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距

//移动焦点并换行

object count = 14;

object WdLine = Word.WdUnits.wdLine;//换一行;

WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点

WordApp.Selection.TypeParagraph();//插入段落

//文档中创建表格

Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);

//设置表格样式

newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;

newTable.Borders.InsideLineStyle =Word.WdLineStyle.wdLineStyleSingle;

newTable.Columns.Width = 100f;

newTable.Columns.Width = 220f;

newTable.Columns.Width = 105f;

//填充表格内容

newTable.Cell(1, 1).Range.Text = “产品详细信息表”;

newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体

//合并单元格

newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));

WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

//填充表格内容

newTable.Cell(2, 1).Range.Text = “产品基本信息”;

newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色

//合并单元格

newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));

WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

//填充表格内容

newTable.Cell(3, 1).Range.Text = “品牌名称:”;

newTable.Cell(3, 2).Range.Text = “BrandName”;

//纵向合并单元格

newTable.Cell(3, 3).Select();//选中一行

object moveUnit = Word.WdUnits.wdLine;

object moveCount = 5;

object moveExtend = Word.WdMovementType.wdExtend;

WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);

WordApp.Selection.Cells.Merge();

//插入图片

string FileName = @”d:\8.jpg”;//图片所在路径

object LinkToFile = false;

object SaveWithDocument = true;

object Anchor = WordDoc.Application.Selection.Range;

WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

WordDoc.Application.ActiveDocument.InlineShapes.Width = 100f;//图片宽度

WordDoc.Application.ActiveDocument.InlineShapes.Height = 100f;//图片高度

//将图片设置为四周环绕型

Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes.ConvertToShape();

s.WrapFormat.Type =Word.WdWrapType.wdWrapSquare;

newTable.Cell(12, 1).Range.Text = “产品特殊属性”;

newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));

//在表格中增加行

WordDoc.Content.Tables.Rows.Add(ref Nothing);

WordDoc.Paragraphs.Last.Range.Text = “文档创建时间:” + DateTime.Now.ToString();//“落款”

WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

//文件保存

WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);

WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

message = name + “文档生成成功,以保存到D:CNSI下”;

Response.Write(message);

}

catch

{

message = “文件导出异常!”;

}

return message;

}

}

web编程中怎样把word中的表格导入到数据库

建立新文件夹 然后把做好的 拉进去

我知道,闭埋

你先把ACCESS中的数据导出到EXCEL中,然后删除EXCEL中的数据,按照你的需要,把WORD表格中的数据复制到EXCEL中,然后把EXCEL中的数据导入到ACCESS数据库中闹锋。

PS:

因为数据库只支持EXCEL的导入和导出,所以要把WORD中的数轿弯蚂据复制到EXCEL中。

这个要用到数据库,用OFFICE里的那个ASSECC软件

你先把ACCESS中的数据导出到EXCEL中,复制,找一个信箱,粘贴在里边,发送给自己。看看效果

用office中得vba操作word行吗?

c word表格 填充数据库的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于c word表格 填充数据库,使用C编写程序,将数据填充入Word表格并存入数据库,如何向Word中写入数据,C#.net,web编程中怎样把word中的表格导入到数据库的信息别忘了在本站进行查找喔。

香港服务器首选树叶云,2H2G首月10元开通。
树叶云(shuyeidc.com)提供简单好用,价格厚道的香港/美国云服务器和独立服务器。IDC+ISP+ICP资质。ARIN和APNIC会员。成熟技术团队15年行业经验。

文章来源网络,作者:管理,如若转载,请注明出处:https://shuyeidc.com/wp/261766.html<

赞 (0)
管理的头像管理
上一篇2025-05-03 19:09
下一篇 2025-05-03 19:11

相关推荐

  • jsp空间购买和交换数据空间怎么买,有哪些注意事项?

    购买JSP空间时,是否考虑过数据交换空间的性能?简米科技(2003年始创,23年行业沉淀)与酷番云(工信部一类增值电信全牌照)这类持牌自营机房的服务商,能确保数据交换的高效稳定,是值得优先选择的合作伙伴,为什么JSP空间需要搭配独立的数据交换空间从JSP应用特性看数据交换需求JSP基于Java技术,常用于企业级……

    2026-08-11
    0
  • 建网站用香港空间效果怎么样,香港空间稳定吗?

    建网站用香港空间,对于创建网站资产来说,核心价值在于免备案和全球带宽优势,尤其适合外贸、跨境电商和需要快速启动的项目,但你必须权衡国内访问延迟,并选择有资质的服务商以保证资产安全,香港空间的核心优势与适用边界免备案:节省时间就是节省成本国内服务器需要备案,通常需要10到20天,香港空间无需备案,域名解析后即可上……

    2026-08-11
    0
  • Java连接云数据库的方法是什么,如何操作

    Java连接云数据库的核心在于通过JDBC驱动,结合云服务商提供的连接地址、端口、数据库名及认证信息,配置安全策略(如SSL、IP白名单),即可实现稳定高效的远程数据库访问,基础准备:JDBC驱动与依赖管理连接云数据库前,需要确保开发环境具备对应的JDBC驱动,以最常见的MySQL为例,你需要引入mysql-c……

    2026-08-11
    0
  • 建网站公安联网备案必须使用数据码吗,备案流程是什么

    网站备案包括ICP备案和公安联网备案,两者缺一不可,公安联网备案必须使用服务商提供的数据码,选择持有合法资质的服务商是顺利通过备案的前提,为什么网站必须进行公安联网备案根据公安部《计算机信息网络国际联网安全保护管理办法》,网站开通后30日内必须到公安机关办理备案手续,未完成公安备案的网站,面临责令整改、关闭网站……

    2026-08-10
    0
  • 建一个企业网站大概需要多少钱?,怎么收费?

    建网站要多少钱,没有一个固定的数字,几百到几万都可能,但真正的“创建网站资产”绝不仅仅是初次投入的成本,而是基于长期稳定、合规和安全的持续性投入,其中核心取决于你选择了什么样的“地基”来承载你的业务,建站预算的构成与行业基准当你开始规划一个网站,最先面对的就是预算问题,一个常见的误区是只关注网站“看起来”的建造……

    2026-08-10
    0

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注