首页 文章

如何在magento 1.9.2中导入/导出简单和可配置产品?

提问于
浏览
0

如何在magento 1.9.2中导入/导出简单和可配置产品?我需要通过Magento中的csv导入可配置产品和简单产品但上传但不能与Configurable和简单产品联合,任何人都可以帮助我吗?

sku,_type,_attribute_set,_product_websites,title,price,description,short_description,weight,status,qty,name,visibility,tax_class_id
bssfw011,simple,indianink,base,10,999,BLUE SUIT SETS FOR WOMEN,BLUE SUIT SETS FOR WOMEN,100,1,55,BLUE SUIT SETS FOR WOMEN,1,0
bssfw012,simple,indianink,base,8,999,BLUE SUIT SETS FOR WOMEN,BLUE SUIT SETS FOR WOMEN,100,1,55,BLUE SUIT SETS FOR WOMEN,1,0
bssfw013,simple,indianink,base,9,999,BLUE SUIT SETS FOR WOMEN,BLUE SUIT SETS FOR WOMEN,100,1,55,BLUE SUIT SETS FOR WOMEN,1,0
bssfw014,simple,indianink,base,5,999,BLUE SUIT SETS FOR WOMEN,BLUE SUIT SETS FOR WOMEN,100,1,56,BLUE SUIT SETS FOR WOMEN,1,0
bssfw015,configurable,indianink,base,0,999,BLUE SUIT SETS FOR WOMEN,BLUE SUIT SETS FOR WOMEN,100,1,0,BLUE SUIT SETS FOR WOMEN,4,0

1 回答

  • 1

    嗨创建文件app \ code \ core \ Mage \ Catalog \ Model \ Convert \ Adapter \ Productwithlinks.php

    <?php
    /**
     * Magento
     *
     * NOTICE OF LICENSE
     *
     * This source file is subject to the Open Software License (OSL 3.0)
     * that is bundled with this package in the file LICENSE.txt.
     * It is also available through the world-wide-web at this URL:
     * http://opensource.org/licenses/osl-3.0.php
     * If you did not receive a copy of the license and are unable to
     * obtain it through the world-wide-web, please send an email
     * to license@magentocommerce.com so we can send you a copy immediately.
     *
     * DISCLAIMER
     *
     * Do not edit or add to this file if you wish to upgrade Magento to newer
     * versions in the future. If you wish to customize Magento for your
     * needs please refer to http://www.magentocommerce.com for more information.
     *
     * @category   Mage
     * @package    Mage_Catalog
     * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
     * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
     */
    
    
    class Mage_Catalog_Model_Convert_Adapter_Productwithlinks
        extends Mage_Catalog_Model_Convert_Adapter_Product
    {
    
        /**
         * Save product (import)
         *
         * @param array $importData
         * @throws Mage_Core_Exception
         * @return bool
         */
        public function saveRow(array $importData)
        {
            $product = $this->getProductModel();
            $product->setData(array());
            if ($stockItem = $product->getStockItem()) {
                $stockItem->setData(array());
            }
    
            if (empty($importData['store'])) {
                if (!is_null($this->getBatchParams('store'))) {
                    $store = $this->getStoreById($this->getBatchParams('store'));
                } else {
                    $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
                    Mage::throwException($message);
                }
            } else {
                $store = $this->getStoreByCode($importData['store']);
            }
    
            if ($store === false) {
                $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
                Mage::throwException($message);
            }
            if (empty($importData['sku'])) {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku');
                Mage::throwException($message);
            }
            $product->setStoreId($store->getId());
            $productId = $product->getIdBySku($importData['sku']);
      $new = true; // fix for duplicating attributes error
            if ($productId) {
                $product->load($productId);
       $new = false; // fix for duplicating attributes error
            }
            $productTypes = $this->getProductTypes();
            $productAttributeSets = $this->getProductAttributeSets();
    
            /**
            * Check product define type
            */
            if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
                $value = isset($importData['type']) ? $importData['type'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
                Mage::throwException($message);
            }
            $product->setTypeId($productTypes[strtolower($importData['type'])]);
            /**
            * Check product define attribute set
            */
            if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
                $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set');
                Mage::throwException($message);
            }
            $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
    
            foreach ($this->_requiredFields as $field) {
                $attribute = $this->getAttribute($field);
                if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                    $message = Mage::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field);
                    Mage::throwException($message);
                }
            }
    
      //================================================
      // this part handles configurable products and links 
      //================================================
    
      if ($importData['type'] == 'configurable') {
       $product->setCanSaveConfigurableAttributes(true);
       $configAttributeCodes = $this->userCSVDataAsArray($importData['config_attributes']);
       $usingAttributeIds = array();
       foreach($configAttributeCodes as $attributeCode) {
        $attribute = $product->getResource()->getAttribute($attributeCode);
        if ($product->getTypeInstance()->canUseAttribute($attribute)) {
         if ($new) { // fix for duplicating attributes error
          $usingAttributeIds[] = $attribute->getAttributeId();
         }
        }
       }
       if (!empty($usingAttributeIds)) {
        $product->getTypeInstance()->setUsedProductAttributeIds($usingAttributeIds);
        $product->setConfigurableAttributesData($product->getTypeInstance()->getConfigurableAttributesAsArray());
        $product->setCanSaveConfigurableAttributes(true);
        $product->setCanSaveCustomOptions(true);
       }
       if (isset($importData['associated'])) {
        $product->setConfigurableProductsData($this->skusToIds($importData['associated'], $product));
       }
      }
    
            /**
             * Init product links data (related, upsell, crosssell, grouped)
             */
        if (isset($importData['related'])) {
          $linkIds = $this->skusToIds($importData['related'], $product);
          if (!empty($linkIds)) {
            $product->setRelatedLinkData($linkIds);
          }
        }
        if (isset($importData['upsell'])) {
          $linkIds = $this->skusToIds($importData['upsell'], $product);
          if (!empty($linkIds)) {
            $product->setUpSellLinkData($linkIds);
          }
        }
        if (isset($importData['crosssell'])) {
          $linkIds = $this->skusToIds($importData['crosssell'], $product);
          if (!empty($linkIds)) {
            $product->setCrossSellLinkData($linkIds);
          }
        }
        if (isset($importData['grouped'])) {
          $linkIds = $this->skusToIds($importData['grouped'], $product);
          if (!empty($linkIds)) {
            $product->setGroupedLinkData($linkIds);
          }
        }
    
      //================================================
    
    
    
    
    
            if (isset($importData['category_ids'])) {
                $product->setCategoryIds($importData['category_ids']);
            }
    
            foreach ($this->_ignoreFields as $field) {
                if (isset($importData[$field])) {
                    unset($importData[$field]);
                }
            }
    
            if ($store->getId() != 0) {
                $websiteIds = $product->getWebsiteIds();
                if (!is_array($websiteIds)) {
                    $websiteIds = array();
                }
                if (!in_array($store->getWebsiteId(), $websiteIds)) {
                    $websiteIds[] = $store->getWebsiteId();
                }
                $product->setWebsiteIds($websiteIds);
            }
    
            if (isset($importData['websites'])) {
                $websiteIds = $product->getWebsiteIds();
                if (!is_array($websiteIds)) {
                    $websiteIds = array();
                }
                $websiteCodes = split(',', $importData['websites']);
                foreach ($websiteCodes as $websiteCode) {
                    try {
                        $website = Mage::app()->getWebsite(trim($websiteCode));
                        if (!in_array($website->getId(), $websiteIds)) {
                            $websiteIds[] = $website->getId();
                        }
                    }
                    catch (Exception $e) {}
                }
                $product->setWebsiteIds($websiteIds);
                unset($websiteIds);
            }
    
            foreach ($importData as $field => $value) {
                if (in_array($field, $this->_inventorySimpleFields)) {
                    continue;
                }
                if (in_array($field, $this->_imageFields)) {
                    continue;
                }
    
                $attribute = $this->getAttribute($field);
                if (!$attribute) {
                    continue;
                }
    
                $isArray = false;
                $setValue = $value;
    
                if ($attribute->getFrontendInput() == 'multiselect') {
                    $value = split(self::MULTI_DELIMITER, $value);
                    $isArray = true;
                    $setValue = array();
                }
    
                if ($value && $attribute->getBackendType() == 'decimal') {
                    $setValue = $this->getNumber($value);
                }
    
                if ($attribute->usesSource()) {
                    $options = $attribute->getSource()->getAllOptions(false);
    
                    if ($isArray) {
                        foreach ($options as $item) {
                            if (in_array($item['label'], $value)) {
                                $setValue[] = $item['value'];
                            }
                        }
                    }
                    else {
                        $setValue = null;
                        foreach ($options as $item) {
                            if ($item['label'] == $value) {
                                $setValue = $item['value'];
                            }
                        }
                    }
                }
    
                $product->setData($field, $setValue);
            }
    
            if (!$product->getVisibility()) {
                $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
            }
    
            $stockData = array();
            $inventoryFields = $product->getTypeId() == 'simple' ? $this->_inventorySimpleFields : $this->_inventoryOtherFields;
            foreach ($inventoryFields as $field) {
                if (isset($importData[$field])) {
                    if (in_array($field, $this->_toNumber)) {
                        $stockData[$field] = $this->getNumber($importData[$field]);
                    }
                    else {
                        $stockData[$field] = $importData[$field];
                    }
                }
            }
            $product->setStockData($stockData);
    
            $imageData = array();
            foreach ($this->_imageFields as $field) {
                if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
                    if (!isset($imageData[$importData[$field]])) {
                        $imageData[$importData[$field]] = array();
                    }
                    $imageData[$importData[$field]][] = $field;
                }
            }
    
            foreach ($imageData as $file => $fields) {
                try {
                    $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $file, $fields);
                }
                catch (Exception $e) {}
            }
    
            $product->setIsMassupdate(true);
            $product->setExcludeUrlRewrite(true);
    
            $product->save();
    
            return true;
        }
    
    
    
    
        protected function userCSVDataAsArray($data) {
      return explode(',', str_replace(" ", "", $data));
     }
    
     protected function skusToIds($userData,$product) {
      $productIds = array();
      foreach ($this->userCSVDataAsArray($userData) as $oneSku) {
       if (($a_sku = (int)$product->getIdBySku($oneSku)) > 0) {
        parse_str("position=", $productIds[$a_sku]);
       }
      }
      return $productIds;
     }
    
    
    }
    

    和Go-> admin-> system-> import / export-> Dataflow - Advanced Profiles-> Add New Template-> Profile Name - > ImportConfigurableProduct and Actions XML - > Paste Code

    <action type="dataflow/convert_adapter_io" method="load">
        <var name="type">file</var>
        <var name="path">var/import</var>
        <var name="filename"><![CDATA[import_product.csv]]></var>
        <var name="format"><![CDATA[csv]]></var>
    </action>
    
    <action type="dataflow/convert_parser_csv" method="parse">
        <var name="delimiter"><![CDATA[,]]></var>
        <var name="enclose"><![CDATA["]]></var>
        <var name="fieldnames">true</var>
        <var name="store"><![CDATA[0]]></var>
        <var name="number_of_records">1</var>
        <var name="decimal_separator"><![CDATA[.]]></var>
        <var name="adapter">catalog/convert_adapter_productwithlinks</var>
        <var name="method">parse</var>
    </action>
    

    然后goto-> Var create - > import directory - > put file import_product.csv

    CSV方法是

    网站,attribute_set,类型,category_ids,SKU,has_options,名称,meta_title,meta_description,图像,small_image,缩略图,url_key,url_path,config_attributes,custom_design,page_layout,options_container,image_label,small_image_label,thumbnail_label,country_of_manufacture,msrp_enabled,msrp_display_actual_price_type,gift_message_available, size_guide_image,设计,color_linked_product,价格,special_price,厂商建议零售价,地位,知名度,tax_class_id,大小,套,SHORT_DESCRIPTION,描述,size_guide,size_fit,material_care,meta_keyword,custom_layout_update,special_from_date,special_to_date,news_from_date,news_to_date,custom_design_from,custom_design_to,inventory_qty, min_qty,use_config_min_qty,is_qty_decimal,缺货,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,low_stock_date,notify_stock_qty,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,stock_status_changed_auto,use_config_qty_increments,qty_increments,use_config_enable_q ty_inc,enable_qty_increments,is_decimal_divided,stock_status_changed_automatically,use_config_enable_qty_increments,PRODUCT_NAME,STORE_ID,product_type_id,product_status_changed,product_changed_websites,画廊,相关的,追加销售,crosssell,tier_prices,关联,bundle_options,分组,group_price_price,downloadable_options,downloadable_sample_options,super_attribute_pricing,product_tags,重量,颜色, is_recurring

相关问题