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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做了一些读取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("直接经济损失分布

<think>嗯,用户想用Java读取文件属性并导出为压缩的SHP文件。我需要先理清楚步骤。首先,SHP文件是GIS常用的格式,通常需要Shapefile库,比如GeoTools。然后,用户提到导出为压缩包,可能需要将生成的SHP文件相关文件(如.shp, .dbf, .shx等)打包成ZIP。 根据引用[2][5],GeoTools可以处理SHP的读写坐标系统。用户需要读取文件属性,可能是指读取现有文件的属性,或者从其他数据源生成属性。然后导出SHP,并压缩成ZIP。 步骤应该是:1. 使用GeoTools创建FeatureType,定义属性几何类型。2. 创建Feature实例,填充数据。3. 写入到Shapefile。4. 将生成的文件打包成ZIP,可能需要用Java的ZipOutputStream。 另外,引用[2]提到处理ZIP压缩包直读,但这里用户需要导出为压缩包,所以解压的逆过程,即压缩。需要注意临时文件的处理,避免脏文件,可以用临时目录或者内存操作,但SHP文件可能较大,用临时目录更实际。 用户可能需要示例代码,所以需要提供创建Feature、写入Shapefile,然后压缩的代码片段。同时,要处理坐标系统,比如引用[5]中的投影问题,可能需要设置正确的CRS。 可能的问题:文件路径处理,确保所有必要文件(.shp, .dbf等)都被正确写入压缩。GeoTools的依赖配置,用户可能需要添加Maven依赖。 总结步骤:配置GeoTools依赖,创建数据模型,写入Shapefile,收集所有生成的文件,用ZipOutputStream压缩成ZIP,清理临时文件。</think>### 使用Java读取文件属性并导出压缩SHP文件的实现步骤 #### 一、技术选型与依赖准备 1. **核心库选择**: - **GeoTools**:GIS数据处理核心库,支持SHP文件读写、坐标系转换[^2][^5] - **Java内置压缩库**:`java.util.zip`处理ZIP压缩包 2. **Maven依赖配置**: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>25.1</version> </dependency> <dependency> <groupId>org.geotools</groupId> <artifactId>gt-epsg-hsql</artifactId> <version>25.1</version> </dependency> ``` #### 二、核心实现流程 $$ \begin{aligned} &\text{1. 定义数据结构} \rightarrow \text{2. 创建Feature集合} \\ &\rightarrow \text{3. 写入Shapefile} \rightarrow \text{4. 压缩为ZIP} \end{aligned} $$ #### 三、完整代码示例 ```java // 1. 创建FeatureType定义 SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder(); typeBuilder.setName("Location"); typeBuilder.setCRS(DefaultGeographicCRS.WGS84); // 坐标系设置[^5] typeBuilder.add("geometry", Point.class); typeBuilder.add("name", String.class); typeBuilder.add("id", Integer.class); SimpleFeatureType featureType = typeBuilder.buildFeatureType(); // 2. 创建Feature集合 SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType); List<SimpleFeature> features = new ArrayList<>(); featureBuilder.add(new GeometryFactory().createPoint(new Coordinate(116.40, 39.90))); featureBuilder.add("北京地标"); featureBuilder.add(1); features.add(featureBuilder.buildFeature("point1")); // 3. 写入临时目录 File tempDir = Files.createTempDirectory("shp_export").toFile(); File shpFile = new File(tempDir, "output.shp"); FeatureCollection<SimpleFeatureType, SimpleFeature> collection = new ListFeatureCollection(featureType, features); try (ShapefileDataStore dataStore = new ShapefileDataStore(shpFile.toURI().toURL())) { dataStore.createSchema(featureType); try (FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend()) { for (SimpleFeature feature : collection) { SimpleFeature newFeature = writer.next(); newFeature.setAttributes(feature.getAttributes()); writer.write(); } } } // 4. 压缩为ZIP try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("output.zip"))) { for (File file : tempDir.listFiles()) { zipOut.putNextEntry(new ZipEntry(file.getName())); Files.copy(file.toPath(), zipOut); zipOut.closeEntry(); } FileUtils.deleteDirectory(tempDir); // 清理临时文件[^2] } ``` #### 四、关键优化点 1. **内存管理**:使用临时目录避免内存溢出[^2] 2. **坐标系处理**:通过`setCRS()`指定投影系统(如CGCS2000)[^5] 3. **异常处理**:应添加try-with-resources确保资源释放
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值