读取shp属性表导出为excel表格和写入word文档

这篇博客介绍了如何读取shp属性表,将数据导出为Excel表格并写入到Word文档中。作者提供了一段C#代码,该代码首先检查输入文件的正确性,然后创建数据表,填充属性信息,最后使用Word和Excel API将数据写入相应文件。代码涉及了文件操作、数据转换和Office应用程序的交互。
摘要由CSDN通过智能技术生成

最近做了一些读取shp属性表另存为excel表格和写入word文档的小事情,把思路和代码记下来,以备以后查看,各位大神看到请绕道,高抬贵手大笑

 条件如下:必备一个word文档,且里面必须有一张空表,假如我只需要读取shp属性表的两个字段:City(市名)和affcountyN(受灾县数量)

具体代码如下:

 public class Helper
    {

     public bool Execute(string excelPath, string docPath, string shpPath, out string message)
        {

            return ExecuteEX(excelPath, docPath, shpPath, out message);
        }
      
        /// <summary>
        /// 执行函数
        /// </summary>
        /// <param name="excelPath">excel路径</param>
        /// <param name="docPath">文档路径</param>
        /// <param name="shpPath">shp文件路径</param>
        /// <returns></returns>
        private bool ExecuteEX(string excelPath, string docPath, string shpPath, out string message)
        {
            try
            {
                if (!judgeInOrOutFile(excelPath, docPath, shpPath))
                {
                    message = "文件输入不正确!";
                    return false;
                }
                //判断excel文件是否存在,若存在删除
                if (File.Exists(excelPath))
                {
                    File.Delete(excelPath);
                }
                string docResultPath = Path.Combine(Path.GetDirectoryName(docPath), "data.doc");
                //判断doc文件是否存在,若存在删除
                if (File.Exists(docResultPath))
                {
                    File.Delete(docResultPath);
                }
                //拷贝一份word文档
                File.Copy(docPath, docResultPath);
                //打开shp
                string folder = Path.GetDirectoryName(shpPath);
                IWorkspaceFactory pWSF = new ShapefileWorkspaceFactoryClass();
                IFeatureWorkspace pWS = (IFeatureWorkspace)pWSF.OpenFromFile(folder, 0);
                IFeatureClass pFeatureClass = pWS.OpenFeatureClass(Path.GetFileNameWithoutExtension(shpPath));

                //获得shp属性表并创建dataTable
                IFeatureCursor featureCursor = pFeatureClass.Search(null, false);
                IFeature feature = featureCursor.NextFeature();
                DataTable dt = NewDataTable();
                string value = null;
                while (feature != null)
                {
                    //新建行
                    DataRow dr = dt.NewRow();
                    //从shp属性表中获得city属性
                    value = feature.get_Value(pFeatureClass.FindField("City")).ToString();
                    //转换为汉字
                    string strvalue = GetVlue(value);
                    //赋值
                    dr["City"] = strvalue;
                    value = feature.get_Value(pFeatureClass.FindField("affcountyN")).ToString();
                    dr["affcountyN"] = Math.Round(TODouble(value), 2);
                    //datatable添加此行
                    dt.Rows.Add(dr);
                    feature = featureCursor.NextFeature();
                }
                //创建一个wordApplication
                WordOper wordOper = new WordOper();
                wordOper.OpenAndActive(docResultPath, false, false);
                //表格赋值
                wordOper.TableValue(dt);
                wordOper.Save();
                wordOper.Close();

                //改变表格列名
                dt.Columns["City"].ColumnName = "地区";
                dt.Columns["affcountyN"].ColumnName = "直接经济损失(万元) ";
                //另存表格
                ExcelOper excel = new ExcelOper();

                Hashtable hashTable = new Hashtable();
                hashTable.Add("直接经济损失分布产品", dt)

在Python中,你可以使用一些GIS库如geopandas和openpyxl来实现.shp文件到Excel文件的批量转换。以下是一个简单的步骤: 1. **安装必要的库**: 首先需要安装`geopandas`用于处理.shp文件,`openpyxl`用于创建Excel文件。可以使用pip安装: ``` pip install geopandas openpyxl ``` 2. **读取.shp文件**: 使用`geopandas`的`read_file`函数读取.shp文件,假设.shp文件位于"data"目录下: ```python import geopandas as gpd shapes = gpd.read_file("data/*.shp") ``` 3. **数据预处理**: 根据需要清洗、整理或转换数据,例如添加新列或删除不需要的信息。 4. **保存到Excel**: 使用`openpyxl`库创建一个新的Excel工作簿,并将数据写入: ```python import os from openpyxl import Workbook # 创建一个Excel工作簿 wb = Workbook() ws = wb.active for idx, shape in shapes.iterrows(): # 将几何信息和其他属性写入当前行 row_data = [shape.geometry.wkt, shape['column_name']] # 更改'column_name'为你的.shp文件中的实际字段名 ws.append(row_data) # 保存文件 file_name = 'output.xlsx' path = os.path.join('data', file_name) wb.save(path) ``` 5. **批量操作**: 如果有多个.shp文件需要处理,可以用os模块遍历文件夹,对每个.shp文件重复以上过程: ```python shp_files = [f for f in os.listdir("data") if f.endswith(".shp")] for file in shp_files: # 重复上述读取、处理和保存步骤 ``` 记得替换代码中的'column_name'为你的.shp文件中的实际字段名,并根据需要调整数据处理部分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值