最近做了一些读取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)