使用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

相关推荐

  • 个人主题怎么制作?

    制作个人主题是一个将个人风格、兴趣或专业领域转化为视觉化或结构化内容的过程,无论是用于个人博客、作品集、社交媒体账号还是品牌形象,核心都是围绕“个人特色”展开,以下从定位、内容规划、视觉设计、技术实现四个维度,详细拆解制作个人主题的完整流程,明确主题定位:找到个人特色的核心主题定位是所有工作的起点,需要先回答……

    2025-11-20
    0
  • 社群营销管理关键是什么?

    社群营销的核心在于通过建立有温度、有价值、有归属感的社群,实现用户留存、转化和品牌传播,其管理需贯穿“目标定位-内容运营-用户互动-数据驱动-风险控制”全流程,以下从五个维度展开详细说明:明确社群定位与目标社群管理的首要任务是精准定位,需明确社群的核心价值(如行业交流、产品使用指导、兴趣分享等)、目标用户画像……

    2025-11-20
    0
  • 香港公司网站备案需要什么材料?

    香港公司进行网站备案是一个涉及多部门协调、流程相对严谨的过程,尤其需兼顾中国内地与香港两地的监管要求,由于香港公司注册地与中国内地不同,其网站若主要服务内地用户或使用内地服务器,需根据服务器位置、网站内容性质等,选择对应的备案路径(如工信部ICP备案或公安备案),以下从备案主体资格、流程步骤、材料准备、注意事项……

    2025-11-20
    0
  • 如何企业上云推广

    企业上云已成为数字化转型的核心战略,但推广过程中需结合行业特性、企业痛点与市场需求,构建系统性、多维度的推广体系,以下从市场定位、策略设计、执行落地及效果优化四个维度,详细拆解企业上云推广的实践路径,精准定位:明确目标企业与核心价值企业上云并非“一刀切”的方案,需先锁定目标客户群体,提炼差异化价值主张,客户分层……

    2025-11-20
    0
  • PS设计搜索框的实用技巧有哪些?

    在PS中设计一个美观且功能性的搜索框需要结合创意构思、视觉设计和用户体验考量,以下从设计思路、制作步骤、细节优化及交互预览等方面详细说明,帮助打造符合需求的搜索框,设计前的规划明确使用场景:根据网站或APP的整体风格确定搜索框的调性,例如极简风适合细线条和纯色,科技感适合渐变和发光效果,电商类则可能需要突出搜索……

    2025-11-20
    0

发表回复

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